Using a SQL table function in a join in a query

I think this has to qualify as one of the most useful things I’ve learnt in SQL Server this month. How to to use a table function in a join in a query.

It’s called the APPLY operator, and it only works on SQL 2005 and above. Here’s an example I found:

select a.PersonId, b.Passportnumber,
p.col1, p.col2, p.col3 from Person a OUTER APPLY dbo.fn_Passport(a.PersonId) p

You use CROSS APPLY when the function must return 1 or more rows to retain the Person record. Use OUTER APPLY to keep the Person record even if the function results in no rows.

CROSS APPLY similar to INNER JOIN
OUTER APPLY similar to OUTER JOIN

There’s some real power in this, for example, you can write a query that returns to the first X rows from each category of people, as illustrated by this article ‘Using CROSS APPLY in SQL Server 2005‘.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s