Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause on a column that's a result of a UDF

I have a user defined function (e.g. myUDF(a,b)) that returns an integer.

I am trying to ensure this function will be called only once and its results can be used as a condition in the WHERE clause:

SELECT col1, col2, col3, 
       myUDF(col1,col2) AS X
From myTable
WHERE x>0

SQL Server tries to detect x as column, but it's really an alias for a computed value.

How can you re-write this query so that the filtering can be done on the computed value without having to execute the UDF more than once?

like image 709
Gzim Avatar asked Dec 01 '22 05:12

Gzim


1 Answers

With Tbl AS 
(SELECT col1, col2, col3, myUDF(col1,col2) AS X  
        From table myTable  )

SELECT * FROM Tbl WHERE X > 0
like image 139
Baaju Avatar answered Dec 04 '22 01:12

Baaju