I Need to pass the return value of a function that is selected in previous column and pass it as parameter to a following function in the same row. I cannot use the alias:
What I want to have is:
SELECT
dbo.GetSecondID(f.ID) as SecondID,
dbo.GetThirdID(SecondID) as ThirdID
FROM Foo f
Any workaround? Thank you!
EDIT:
The method dbo.GetSecondID()
is very heavy and I am dealing with a couple of million records in the table. It is not wise to pass the method as a parameter.
Did you mean this:
The way that SQL is designed, it is intended that all columns can be computed in parallel (in theory). This means that you cannot have one column's value depend on the result of computing a different column (within the same
SELECT
clause).To be able to reference the column, you might introduce a subquery:
or a CTE:
If you're building up calculations multiple times (e.g. A depends on B, B depends on C, C depends on D...), then the CTE form usually ends up looking neater (IMO).
Bingo! The secret stand in applying a
CROSS APPLY
. The following code was helpfulEDIT:
This only works if
SecondID
is unique (only one record is returned) orGROUP BY
is used