snippetsqlCritical
How to join a table with a table valued function?
Viewed 0 times
withvaluedfunctionjoinhowtable
Problem
I have a user defined function:
Now I want to join this on another table, like so:
In other words, for all
What's the syntax to do this?
create function ut_FooFunc(@fooID bigint, @anotherParam tinyint)
returns @tbl Table (Field1 int, Field2 varchar(100))
as
begin
-- blah blah
endNow I want to join this on another table, like so:
select f.ID, f.Desc, u.Field1, u.Field2
from Foo f
join ut_FooFunc(f.ID, 1) u -- doesn't work
where f.SomeCriterion = 1In other words, for all
Foo records where SomeCriterion is 1, I want to see the Foo ID and Desc, alongside the values of Field1 and Field2 that are returned from ut_FooFunc for an input of Foo.ID.What's the syntax to do this?
Solution
You need
The definition of table expressions involved in joins must be stable. I.e. They can't be correlated such that the table expression means something different dependant on the value of a row in another table.
CROSS APPLY not join.The definition of table expressions involved in joins must be stable. I.e. They can't be correlated such that the table expression means something different dependant on the value of a row in another table.
select f.ID, f.Desc, u.Field1, u.Field2
from Foo f
Cross apply ut_FooFunc(f.ID, 1) u
where f.SomeCriterion = ...Code Snippets
select f.ID, f.Desc, u.Field1, u.Field2
from Foo f
Cross apply ut_FooFunc(f.ID, 1) u
where f.SomeCriterion = ...Context
StackExchange Database Administrators Q#86143, answer score: 130
Revisions (0)
No revisions yet.