Question

I need to pass SELECT result as parameter of user defined table-parameter function (returning table):

CREATE FUNCTION
...

CREATE TABLE cities
(
    ID int identity not null primary key,
    name varchar(40) unique
)

SELECT ID as startID,FUNCTION( SELECT name FROM cities ) FROM cities WHERE ID=1

Function is intended to SELECT city with ID=1 and result of FUNCTION when parameter is selection of all cities. I need to do it without assigning selection to a variable because I am using this statement inside of CTE where variable can not be assigned (if they can be please tell me :) but it did not work in my case)

Was it helpful?

Solution

By all evidence, that is impossible.

The example in this Technet article shows only one way of using table-valued parameters in a Transact-SQL batch, which may already imply that there is no other method. As you can see, it shows that you need to declare and populate a table-valued variable of the same user-defined type as the parameter in your routine, then pass that variable as an argument.

If that is not enough, I believe the following passage from the article can serve as an explanation of why you need to use a variable:

Transact-SQL passes table-valued parameters to routines by reference to avoid making a copy of the input data.

So, under the covers, your function would not exactly be accepting a set but only a reference to it. You would need to create that reference in your script, and that is what declaring a table-valued variable would be for.

Then there is this (closed) Connect item.

You will probably have to revisit your design if you want/need to avoid variable declaration. If you need help with that, please post a question elaborating on what your query is doing so that a proper alternative could be found.

OTHER TIPS

Tried APPLY?

SELECT c.ID, f.Name
FROM cities c
CROSS APPLY dbo.my_function(c.ID) f
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top