This question has been asked several times, but I still could not figure out the correct answer or the correct way to do this:
...
;WITH CTE AS ( SELECT * FROM ... ) SELECT *, [dbo].[udf_BetaInv](A, B, C, D) AS 'Loss' FROM CTE WHERE (Loss >= @MinRetention)
This does not work, and I cannot create a stored procedure, I cannot use Loss in WHERE, because it does not exist in this area.
I would like to use another CTE to wrap this so that I can put WHERE on the external, but it doesn't work, tried this:
;WITH CTE AS ( SELECT * FROM ... ) SELECT *, [dbo].[udf_BetaInv(A, B, C, D) AS 'Loss' FROM CTE, RESULTS AS (SELECT * FROM CTE) SELECT * FROM RESULTS WHERE (Loss >= @MinRetention)
But it does not compile in SQL Server, I get an error that '(' offsets many lines above, but has nothing to do if I delete the second CTE, it works fine.
I just want to avoid code duplication, I don't want to call my [udf_BetaInv] in select twice, and also in that place.
source share