Search code examples
sqlsql-serversql-server-2016table-valued-parameters

Cross applying or inner joining as subquery for a TVF


Situation:

I have a TVF with one parameter DATE. I want to allow the user to input a list of strings as an additional parameter. I am familiar with user types but I don't want to use it.

Function: dbo.fnExample(@StartDate)

Here are my two options: Option 1

SELECT base.*
FROM (SELECT * FROM dbo.fnExample('2019-05-01')) AS base
INNER JOIN ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
ON base.ColumnA=base2.ColumnA

Option 2 (not working because im not sure how to join on that column with a cross apply).

SELECT *
FROM ( VALUES
('something'),
('something2'),
('n'),
(...)) AS base2(ColumnA)
CROSS APPLY dbo.fnExample('2019-05-01')

Objective:

My question is three-fold. Which would have a better performance? Are there any other options not mentioned above that could be better? What are the limiations from the proposed options ? Thank you for your help!


Solution

  • I think you want JOIN, not APPLY:

    SELECT *
    FROM dbo.fnExample('2019-05-01') f JOIN
         ( VALUES ('something'), ('something2'), ('n'), (...)
         ) AS base2(ColumnA)
         ON  f.columnA = base2.ColumnA;
    

    That is, table-valued functions do not have to be called using APPLY. APPLY is a way to pass in arguments from other FROM-clause entries.