Search code examples
sql-servertable-valued-parameterscross-apply

Using a select query as parameter in a table-valued function


I have a function that takes an integer input and returns a table with the related ids from the below table.

ID  NAME    RELATED_ID
1   a       null
2   b       null
3   c       1
4   d       1

So, select * from fn_getrelatedids(1) returns

ID
1
3
4

I want to use a dynamic parameter as a parameter to the function, i.e.,

select * from fn_getrelatedids (select e.id from entity e where e.name='a')

Obviously this doesn't work.

I tried cross apply:

select e.id from entity e 
cross apply 
(select f.id from fn_getrelatedids (e.id) AS fg
WHERE fg.id = e.id) AS R
WHERE e.name = 'a'

That doesn't return the correct value. The function returns only

ID
1

Am I missing something obvious here?


Solution

  • See if this isn't what you are trying to do.

    select fg.id 
    from entity e 
    cross apply dbo.fn_getrelatedids(e.id) AS fg
    WHERE e.name = 'a'
    

    Edit:to add the right select