Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT result as parameter in user defined table-parameter function

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)

like image 974
user3162968 Avatar asked Nov 18 '25 20:11

user3162968


1 Answers

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.

like image 75
Andriy M Avatar answered Nov 20 '25 10:11

Andriy M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!