32

I have a complex expression calculating a value from a date that I have to use on multiple date columns.
Can I define a temporary local function in my query to avoid copy and pasting this expression. ?

like:

create MyLocalFunc(@ADate datetime) 
returns int as
begin
  blablabla
end

select
  MyLocalFunc(col1), col2, MyLocalFunc(col3), col4, MyLocalFunc(col5)
from
  mytable

As a workaround, I know I can do a CREATE FUNCTION // DROP FUNCTION, but I'd prefer avoid it.

Francesca
  • 21,452
  • 4
  • 49
  • 90
  • See: http://stackoverflow.com/questions/981451/can-i-create-a-one-time-use-function-in-a-script-or-stored-procedure – Weasle Dec 02 '15 at 22:57
  • Does this answer your question? [Can I create a One-Time-Use Function in a Script or Stored Procedure?](https://stackoverflow.com/questions/981451/can-i-create-a-one-time-use-function-in-a-script-or-stored-procedure) – a_hardin Jan 11 '21 at 13:59

2 Answers2

14

No, there is no way -- create/drop is the only choice.

Ben M
  • 22,262
  • 3
  • 67
  • 71
-1

SQL Server supports anonymous blocks by putting the query(ies) inside a BEGIN/END block, but I haven't been able to find an example where someone defined a function within it. Oracle's had the functionality for a while...

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502