Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 692
Francesca Avatar asked Jul 02 '10 19:07

Francesca


People also ask

Can you define a function in SQL?

A function is a set of SQL statements that perform a specific task. Functions foster code reusability. If you have to repeatedly write large SQL scripts to perform the same task, you can create a function that performs that task. Next time instead of rewriting the SQL, you can simply call that function.

Can we create temporary function in SQL Server?

You can't create temporary functions, no.


1 Answers

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

like image 120
Ben M Avatar answered Sep 19 '22 23:09

Ben M