Is it possible to define a local function in a TSQL query?

Francesca picture Francesca · Jul 2, 2010 · Viewed 13.7k times · Source

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.

Answer

Ben M picture Ben M · Jul 2, 2010

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