Question

I was writing a query in t-sql that uses a function in a sub query and came across two questions. Imagine an advertisement table as follows :

AdID- Name

An Options table as follows :

OptionID - OptionName

And a junk table (AdvertisementOptionLink) between these two with two foreign key columns :

AdID - OptionID

Now I want to query the advertisement as user selects the options . I had written a query like this :

SELECT * FROM Advertisement ad
INNER JOIN AdvertisementOptionLink aol
WHERE ad.AdvertisementID IN (SELECT AdvertisementID FROM UDF_GetAdvertisements)

Now UDF_GetAdvertisements is a table valued function that returns list of advertisement that had the specific options.

There are two questions :

  1. Is This UDF_GetAdvertisements function queries all the data for each row ? I mean if I`ve got like 2000 advertisement in my table is it gonna query all those and return all the advertisementIDs? Am i better off saving the function return value in a variable ?

2.In this database there are some advertisement without any options how can I return all advertisement if user selects no options ?

Im using Table-Valued Parameters in t-sql to pass the selected option IDs through a stored procedure. Used a little help from this page : http://www.sommarskog.se/arrays-in-sql-2008.html

Was it helpful?

Solution

You would need to check the execution plan.

WHERE ad.AdvertisementID IN (SELECT AdvertisementID FROM UDF_GetAdvertisements)

will be implemented as a logical semi join operator. The physical join type might be any of merge, hash, or nested loops.

Merge join and Hash join process each input once. Nested loops processes the outer input once and the inner one as many times as there are rows in the outer input. But even if the TVF is shown on the inner side of a nested loops join the result might be cached in a spool rather than repeatedly re-evaluating the TVF.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top