I'd like to pass a table as a parameter into a scaler UDF.
I'd also prefer to restrict the parameter to tables with only one column. (optional)
Is this possible?
EDIT
I don't want to pass a table name, I'd like to pass the table of data (as a reference I presume)
EDIT
I would want my Scaler UDF to basically take a table of values and return a CSV list of the rows.
IE
col1
"My First Value"
"My Second Value"
...
"My nth Value"
would return
"My First Value, My Second Value,... My nth Value"
I'd like to do some filtering on the table though, IE ensuring that there are no nulls and to ensure there are no duplicates. I was expecting something along the lines of:
SELECT dbo.MyFunction(SELECT DISTINCT myDate FROM myTable WHERE myDate IS NOT NULL)
Cutting to the bottom line, you want a query like SELECT x FROM y to be passed into a function that returns the values as a comma separated string.
As has already been explained you can do this by creating a table type and passing a UDT into the function, but this needs a multi-line statement.
You can pass XML around without declaring a typed table, but this seems to need a xml variable which is still a multi-line statement i.e.
The "FOR XML RAW" makes the SQL give you it's result set as some xml.
But you can bypass the variable using Cast(... AS XML). Then it's just a matter of some XQuery and a little concatenation trick:
As long as you use FOR XML RAW all you need do is alias the column you want as Value, as this is hard coded in the function.
The following will enable you to quickly remove the duplicate,null values and return only the valid one as list.
CTE are valid in SQL 2005 , you could then store the values in a temp table and use it with your function.
Step 1: Create a Type as Table with name TableType that will accept a table having one varchar column
Step 2: Create a function that will accept above declared TableType as Table-Valued Parameter and String Value as Separator
Step 3: Pass table with one varchar column to the user-defined type TableType and ',' as separator in the function
you can do something like this
/* CREATE USER DEFINED TABLE TYPE */
/*CREATE FUNCTION WHICH TAKES TABLE AS A PARAMETER */
/*CREATE STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER */
For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html
To obtain the column count on a table, use this:
and to pass a table to a function, try XML as show here: