简体   繁体   中英

Why can't one join with a table returned from a table valued function?

The equivalent of an inner join with table valued functions (TVF) is to use CROSS APPLY (one cannot inner join with a TVF).

I'm wondering why SQL Server disallows joins with the return values of a TVF. Specifically, how is doing a CROSS APPLY on a TVF different than inner joining with a temporary table? Is there a difference in how SQL Server defines the return table of a TVF and a temporary table?

How is doing a CROSS APPLY on a TVF different than inner joining with a temporary table?

You can join a TVF, however you can not use columns from the joining table within the TVF call:

DECLARE @directions VARCHAR(MAX) = 'N, S, W, E' 

SELECT  a.StreetName, s.Value
FROM dbo.Address a 
JOIN dbo.SplitByToken(@directions, ',') s ON a.Direction = s.Value

Here the table valued function creates a table based on a string-list separated by a token. This query would not have a problem, as the result of the table function is known and doesn't change per result of the joining table. It runs once and the resulting table is joined to Address .

It's when the TVF is being used with a column from the joining table that the cross apply must be used instead of join .

SELECT  a.ZIP, g.Long, g.Lat
FROM dbo.Address a 
CROSS APPLY dbo.GeoLocation(a.ZIP) g

Here the Geo Location is calculated based on the table we are using at the time of calculation, and the function needs to be called once per row of the Address table.

Consider the following:

SELECT *
FROM tblFoo
INNER JOIN (fnGetTable(tblFoo.someValue)

fnGetTable returns a new table for each value of tblFoo.someValue . So rather than joining with one table, you're joining with many.

I think ultimately this has to do with temporary tables and db tables being constant objects. Table valued functions don't necessarily return the same table object each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM