views:

41

answers:

3

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.

+2  A: 

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

Ben M
A: 

No, not locally. But you can create a UDF in the database that doesn't have to actually access any data to do its calculation.

Why not make it a permanent UDF?

Toby
+1  A: 

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