SQL Server, variable in IN Clause - sql-server-2008-r2

I want to use a variable inside IN clause, similar to this:
Declare #tt NVARCHAR(MAX)
SET #tt = '02ea2b81-07f0-4660-bca1-81563f65bf65','07728975-cb1d-484c-8894-14f5b793cbef','1071ee4f-a214-443f-8694-0b3e9d2dc77e','120d2881-b04f-4707-a925-e4d941f03201','23af54a7-6666-4747-a74a-c2101cda59b0','260d2ce5-f4f0-4a0b-aa0b-3e1d2b5fcfeb','2710a913-13e7-4300-91f1-2646e2f8449e','2cebc482-4917-4aa3-973b-2481619a78e7','2d2269a4-9164-4dae-a732-90448d761509','2d29c707-1c5f-4e00-bd3c-bfd2ec2c6e29','3ead72a1-de91-47e9-8038-cc504a5274ec','40a03f53-7fd7-488d-922d-3435652219cb','43c93954-2e75-4d47-a53f-848eee609cf1','441e1a59-d397-4981-b770-01fb4594152e','4dacc9df-0536-46f6-af5d-78610ed998cd','4e4910ee-db9b-45ba-8872-2819dcefdc2c','4f9fd3ef-ba81-44bb-8c75-7cf6998e115e','60d9c73f-46c3-4ab1-9a4e-5440d18a0fd8','63e0cc57-1803-473f-847d-f3318f70c993','6510de61-9a1d-4f69-bec4-a744ea2bb847','799e2e55-2ba8-4772-8aff-331ed1817225','7be022db-4d37-4964-9005-3de7c6286027','85ba80c3-5c8b-4097-b5c9-c0d55ac6cf2f','8bc45b07-6a65-43c2-a41e-e791b085a053','8ca2d4a7-f4d6-4b56-aa41-42550e3a11b5','8fa7c3f6-e042-4b93-829f-79b8946a909e','ab34d18a-9482-4146-adb2-7e45e32f8cdd','ac43b44b-651c-4a98-a55f-82878cc8c656','ad9f222c-a98e-44eb-af9e-6f083941be9e','af7e8d24-9126-4d9b-a48a-75bf344c3529','b0e95518-0fef-46ba-81f4-0d1356ebc135','b1f1810f-3044-40b3-b218-5bb02d8922bd','b32ebf2b-f247-4032-8a37-285e4c3488a9','b93a8bb7-c62f-47b7-86ba-0421eb67ca14','c5342d7e-1667-47cb-bccf-91c5e8e9f18c','e2cf46f6-a522-4a96-8a84-f1ce3818c364','f01f4010-a192-43ca-a3bf-157379f4779d','f0f168ec-f043-41ef-90d3-3eac68b90334','f99af706-e1bb-42ba-bdf9-348a3b02c25e','fe691dee-b133-4d1c-90a3-8889cd3482d2';
Select * from table where assessmentId IN(#tt)
But this query is failing, saying Incorrect syntax near ','. The same query will work if I will not use variable in IN clause and directly pass the Id's
Select * from table where AssessmentId IN
('02ea2b81-07f0-4660-bca1-81563f65bf65','07728975-cb1d-484c-8894-14f5b793cbef','1071ee4f-a214-443f-8694-0b3e9d2dc77e','120d2881-b04f-4707-a925-e4d941f03201','23af54a7-6666-4747-a74a-c2101cda59b0','260d2ce5-f4f0-4a0b-aa0b-3e1d2b5fcfeb','2710a913-13e7-4300-91f1-2646e2f8449e','2cebc482-4917-4aa3-973b-2481619a78e7','2d2269a4-9164-4dae-a732-90448d761509','2d29c707-1c5f-4e00-bd3c-bfd2ec2c6e29','3ead72a1-de91-47e9-8038-cc504a5274ec','40a03f53-7fd7-488d-922d-3435652219cb','43c93954-2e75-4d47-a53f-848eee609cf1','441e1a59-d397-4981-b770-01fb4594152e','4dacc9df-0536-46f6-af5d-78610ed998cd','4e4910ee-db9b-45ba-8872-2819dcefdc2c','4f9fd3ef-ba81-44bb-8c75-7cf6998e115e','60d9c73f-46c3-4ab1-9a4e-5440d18a0fd8','63e0cc57-1803-473f-847d-f3318f70c993','6510de61-9a1d-4f69-bec4-a744ea2bb847','799e2e55-2ba8-4772-8aff-331ed1817225','7be022db-4d37-4964-9005-3de7c6286027','85ba80c3-5c8b-4097-b5c9-c0d55ac6cf2f','8bc45b07-6a65-43c2-a41e-e791b085a053','8ca2d4a7-f4d6-4b56-aa41-42550e3a11b5','8fa7c3f6-e042-4b93-829f-79b8946a909e','ab34d18a-9482-4146-adb2-7e45e32f8cdd','ac43b44b-651c-4a98-a55f-82878cc8c656','ad9f222c-a98e-44eb-af9e-6f083941be9e','af7e8d24-9126-4d9b-a48a-75bf344c3529','b0e95518-0fef-46ba-81f4-0d1356ebc135','b1f1810f-3044-40b3-b218-5bb02d8922bd','b32ebf2b-f247-4032-8a37-285e4c3488a9','b93a8bb7-c62f-47b7-86ba-0421eb67ca14','c5342d7e-1667-47cb-bccf-91c5e8e9f18c','e2cf46f6-a522-4a96-8a84-f1ce3818c364','f01f4010-a192-43ca-a3bf-157379f4779d','f0f168ec-f043-41ef-90d3-3eac68b90334','f99af706-e1bb-42ba-bdf9-348a3b02c25e','fe691dee-b133-4d1c-90a3-8889cd3482d2');
How can I use variable in IN clause using the first approach?

You will have to insert the values into a temp table.
Something like
DECLARE #TempTable TABLE(
assessmentId VARCHAR(50)
)
INSERT INTO #TempTable
VALUES
('02ea2b81-07f0-4660-bca1-81563f65bf65'),
('07728975-cb1d-484c-8894-14f5b793cbef'),
('1071ee4f-a214-443f-8694-0b3e9d2dc77e'),
('120d2881-b04f-4707-a925-e4d941f03201'),
('23af54a7-6666-4747-a74a-c2101cda59b0'),
('260d2ce5-f4f0-4a0b-aa0b-3e1d2b5fcfeb'),
('2710a913-13e7-4300-91f1-2646e2f8449e'),
('2cebc482-4917-4aa3-973b-2481619a78e7')
SELECT *
FROM table
where AssessmentId IN (SELECT assessmentId FROM #TempTable)

Since you want to specify multiple values, use a data type that supports multiple values (as opposed to a scalar variable). Here we're using a table variable:
Declare #tt table (value nvarchar(50) not null)
insert into #tt (value) values
('02ea2b81-07f0-4660-bca1-81563f65bf65'),('07728975-cb1d-484c-8894-14f5b793cbef'),('1071ee4f-a214-443f-8694-0b3e9d2dc77e'),
('120d2881-b04f-4707-a925-e4d941f03201'),('23af54a7-6666-4747-a74a-c2101cda59b0'),('260d2ce5-f4f0-4a0b-aa0b-3e1d2b5fcfeb'),
...
Select * from table where assessmentId IN(select value from #tt)

Related

Concatenate string instead of just replacing it

I have a table with standard columns where I want to perform regular INSERTs.
But one of the columns is of type varchar with special semantics. It's a string that's supposed to behave as a set of strings, where the elements of the set are separated by commas.
Eg. if one row has in that varchar column the value fish,sheep,dove, and I insert the string ,fish,eagle, I want the result to be fish,sheep,dove,eagle (ie. eagle gets added to the set, but fish doesn't because it's already in the set).
I have here this Postgres code that does the "set concatenation" that I want:
SELECT string_agg(unnest, ',') AS x FROM (SELECT DISTINCT unnest(string_to_array('fish,sheep,dove' || ',fish,eagle', ','))) AS x;
But I can't figure out how to apply this logic to insertions.
What I want is something like:
CREATE TABLE IF NOT EXISTS t00(
userid int8 PRIMARY KEY,
a int8,
b varchar);
INSERT INTO t00 (userid,a,b) VALUES (0,1,'fish,sheep,dove');
INSERT INTO t00 (userid,a,b) VALUES (0,1,',fish,eagle')
ON CONFLICT (userid)
DO UPDATE SET
a = EXCLUDED.a,
b = SELECT string_agg(unnest, ',') AS x FROM (SELECT DISTINCT unnest(string_to_array(t00.b || EXCLUDED.b, ','))) AS x;
How can I achieve something like that?
Storing comma separated values is a huge mistake to begin with. But if you really want to make your life harder than it needs to be, you might want to create a function that merges two comma separated lists:
create function merge_lists(p_one text, p_two text)
returns text
as
$$
select string_agg(item, ',')
from (
select e.item
from unnest(string_to_array(p_one, ',')) as e(item)
where e.item <> '' --< necessary because of the leading , in your data
union
select t.item
from unnest(string_to_array(p_two, ',')) t(item)
where t.item <> ''
) t;
$$
language sql;
If you are using Postgres 14 or later, unnest(string_to_array(..., ',')) can be replace with string_to_table(..., ',')
Then your INSERT statement gets a bit simpler:
INSERT INTO t00 (userid,a,b) VALUES (0,1,',fish,eagle')
ON CONFLICT (userid)
DO UPDATE SET
a = EXCLUDED.a,
b = merge_lists(excluded.b, t00.b);
I think I was only missing parentheses around the SELECT statement:
INSERT INTO t00 (userid,a,b) VALUES (0,1,',fish,eagle')
ON CONFLICT (userid)
DO UPDATE SET
a = EXCLUDED.a,
b = (SELECT string_agg(unnest, ',') AS x FROM (SELECT DISTINCT unnest(string_to_array(t00.b || EXCLUDED.b, ','))) AS x);

Saving a query in a table

I would like to store a table variable as to be accessed by another query within a function. Here is what I have so far.
CREATE OR REPLACE FUNCTION suggest(p_id INTEGER)
RETURNS TABLE (
r_id INT,
i_id INT
) AS $$
DECLARE
p_record INT[];
BEGIN
SELECT ingredient_id INTO p_record FROM shop_ingredients
WHERE item_id IN
(SELECT item_id FROM basket
WHERE user_id = p_id);
...
I am not sure whether the type of p-record should be an array of INTEGER or a RECORD. Within the function I would like to access such list of values, for example:
HAVING SUM(ingredient_id = ANY(p_record)) >= (COUNT(*)*0.6)
How can I achieve this? I have searched endlessly to understand how to manage this but to no avail.
The problem with creating a table, like so:
CREATE TEMP TABLE IF NOT EXISTS p_record
AS SELECT ingredient_id
FROM shop_ingredients
WHERE item_id IN
(SELECT item_id FROM basket
WHERE user_id = p_id);
is that if p_id parameter changes, the p_record variables does not.
Maybe the following SQL function can help:
create or replace function suggest(p_id int)
returns table (i_id int)
language sql
as
$$
select ingredient_id
from shop_ingredient
where item_id in
(select item_id from basket
where user_id = p_id);
$$;
Note that the SELECT statement column list must exactly match the TABLE clause after RETURNS keyword and this function is only SQL so no need of BEGIN/END block or intermediate record variable.

Run a stored procedure using select columns as input parameters?

I have a select query that returns a dataset with "n" records in one column. I would like to use this column as the parameter in a stored procedure. Below a reduced example of my case.
The query:
SELECT code FROM rawproducts
The dataset:
CODE
1
2
3
The stored procedure:
ALTER PROCEDURE [dbo].[MyInsertSP]
(#code INT)
AS
BEGIN
INSERT INTO PRODUCTS description, price, stock
SELECT description, price, stock
FROM INVENTORY I
WHERE I.icode = #code
END
I already have the actual query and stored procedure done; I just am not sure how to put them both together.
I would appreciate any assistance here! Thank you!
PS: of course the stored procedure is not as simple as above. I just choose to use a very silly example to keep things small here. :)
Here's two methods for you, one using a loop without a cursor:
DECLARE #code_list TABLE (code INT);
INSERT INTO #code_list SELECT code, ROW_NUMBER() OVER (ORDER BY code) AS row_id FROM rawproducts;
DECLARE #count INT;
SELECT #count = COUNT(*) FROM #code_list;
WHILE #count > 0
BEGIN
DECLARE #code INT;
SELECT #code = code FROM #code_list WHERE row_id = #count;
EXEC MyInsertSP #code;
DELETE FROM #code_list WHERE row_id = #count;
SELECT #count = COUNT(*) FROM #code_list;
END;
This works by putting the codes into a table variable, and assigning a number from 1..n to each row. Then we loop through them, one at a time, deleting them as they are processed, until there is nothing left in the table variable.
But here's what I would consider a better method:
CREATE TYPE dbo.code_list AS TABLE (code INT);
GO
CREATE PROCEDURE MyInsertSP (
#code_list dbo.code_list)
AS
BEGIN
INSERT INTO PRODUCTS (
[description],
price,
stock)
SELECT
i.[description],
i.price,
i.stock
FROM
INVENTORY i
INNER JOIN #code_list cl ON cl.code = i.code;
END;
GO
DECLARE #code_list dbo.code_list;
INSERT INTO #code_list SELECT code FROM rawproducts;
EXEC MyInsertSP #code_list = #code_list;
To get this to work I create a user-defined table type, then use this to pass a list of codes into the stored procedure. It means slightly rewriting your stored procedure, but the actual code to do the work is much smaller.
(how to) Run a stored procedure using select columns as input
parameters?
What you are looking for is APPLY; APPLY is how you use columns as input parameters. The only thing unclear is how/where the input column is populated. Let's start with sample data:
IF OBJECT_ID('dbo.Products', 'U') IS NOT NULL DROP TABLE dbo.Products;
IF OBJECT_ID('dbo.Inventory','U') IS NOT NULL DROP TABLE dbo.Inventory;
IF OBJECT_ID('dbo.Code','U') IS NOT NULL DROP TABLE dbo.Code;
CREATE TABLE dbo.Products
(
[description] VARCHAR(1000) NULL,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL
);
CREATE TABLE dbo.Inventory
(
icode INT NOT NULL,
[description] VARCHAR(1000) NULL,
price DECIMAL(10,2) NOT NULL,
stock INT NOT NULL
);
CREATE TABLE dbo.Code(icode INT NOT NULL);
INSERT dbo.Inventory
VALUES (10,'',20.10,3),(11,'',40.10,3),(11,'',25.23,3),(11,'',55.23,3),(12,'',50.23,3),
(15,'',33.10,3),(15,'',19.16,5),(18,'',75.00,3),(21,'',88.00,3),(21,'',100.99,3);
CREATE CLUSTERED INDEX uq_inventory ON dbo.Inventory(icode);
The function:
CREATE FUNCTION dbo.fnInventory(#code INT)
RETURNS TABLE AS RETURN
SELECT i.[description], i.price, i.stock
FROM dbo.Inventory I
WHERE I.icode = #code;
USE:
DECLARE #code TABLE (icode INT);
INSERT #code VALUES (10),(11);
SELECT f.[description], f.price, f.stock
FROM #code AS c
CROSS APPLY dbo.fnInventory(c.icode) AS f;
Results:
description price stock
-------------- -------- -----------
20.10 3
40.10 3
Updated Proc (note my comments):
ALTER PROC dbo.MyInsertSP -- (1) Lose the input param
AS
-- (2) Code that populates the "code" table
INSERT dbo.Code VALUES (10),(11);
-- (3) Use CROSS APPLY to pass the values from dbo.code to your function
INSERT dbo.Products ([description], price, stock)
SELECT f.[description], f.price, f.stock
FROM dbo.code AS c
CROSS APPLY dbo.fnInventory(c.icode) AS f;
This ^^^ is how it's done.

Most succinct way to transform a CSV string to a table in T-SQL?

-- Given a CSV string like this:
declare #roles varchar(800)
select #roles = 'Pub,RegUser,ServiceAdmin'
-- Question: How to get roles into a table view like this:
select 'Pub'
union
select 'RegUser'
union
select 'ServiceAdmin'
After posting this, I started playing with some dynamic SQL. This seems to work, but seems like there might be some security risks by using dynamic SQL - thoughts on this?
declare #rolesSql varchar(800)
select #rolesSql = 'select ''' + replace(#roles, ',', ''' union select ''') + ''''
exec(#rolesSql)
If you're working with SQL Server compatibility level 130 then the STRING_SPLIT function is now the most succinct method available.
Reference link: https://msdn.microsoft.com/en-gb/library/mt684588.aspx
Usage:
SELECT * FROM string_split('Pub,RegUser,ServiceAdmin',',')
RESULT:
value
-----------
Pub
RegUser
ServiceAdmin
See my answer from here
But basically you would:
Create this function in your DB:
CREATE FUNCTION dbo.Split(#origString varchar(max), #Delimiter char(1))
returns #temptable TABLE (items varchar(max))
as
begin
declare #idx int
declare #split varchar(max)
select #idx = 1
if len(#origString )<1 or #origString is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#origString)
if #idx!=0
set #split= left(#origString,#idx - 1)
else
set #split= #origString
if(len(#split)>0)
insert into #temptable(Items) values(#split)
set #origString= right(#origString,len(#origString) - #idx)
if len(#origString) = 0 break
end
return
end
and then call the function and pass in the string you want to split.
Select * From dbo.Split(#roles, ',')
Here's a thorough discussion of your options:
Arrays and Lists in SQL Server
What i do in this case is just using some string replace to convert it to json and open the json like a table. May not be suitable for every use case but it is very simple to get running and works with strings and files. With files you just need to watch your line break character, mostly i find it to be "Char(13)+Char(10)"
declare #myCSV nvarchar(MAX)= N'"Id";"Duration";"PosX";"PosY"
"•P001";223;-30;35
"•P002";248;-28;35
"•P003";235;-26;35'
--CSV to JSON
--convert to json by replacing some stuff
declare #myJson nvarchar(MAX)= '[['+ replace(#myCSV, Char(13)+Char(10), '],[' ) +']]'
set #myJson = replace(#myJson, ';',',') -- Optional: ensure coma delimiters for json if the current delimiter differs
-- set #myJson = replace(#myJson, ',,',',null,') -- Optional: empty in between
-- set #myJson = replace(#myJson, ',]',',null]') -- Optional: empty before linebreak
SELECT
ROW_NUMBER() OVER (ORDER BY (SELECT 0))-1 AS LineNumber, *
FROM OPENJSON( #myJson )
with (
col0 varchar(255) '$[0]'
,col1 varchar(255) '$[1]'
,col2 varchar(255) '$[2]'
,col3 varchar(255) '$[3]'
,col4 varchar(255) '$[4]'
,col5 varchar(255) '$[5]'
,col6 varchar(255) '$[6]'
,col7 varchar(255) '$[7]'
,col8 varchar(255) '$[8]'
,col9 varchar(255) '$[9]'
--any name column count is possible
) csv
order by (SELECT 0) OFFSET 1 ROWS --hide header row
Using SQL Server's built in XML parsing is also an option. Of course, this glosses over all the nuances of an RFC-4180 compliant CSV.
-- Given a CSV string like this:
declare #roles varchar(800)
select #roles = 'Pub,RegUser,ServiceAdmin'
-- Here's the XML way
select split.csv.value('.', 'varchar(100)') as value
from (
select cast('<x>' + replace(#roles, ',', '</x><x>') + '</x>' as xml) as data
) as csv
cross apply data.nodes('/x') as split(csv)
If you are using SQL 2016+, using string_split is better, but this is a common way to do this prior to SQL 2016.
Using BULK INSERT you can import a csv file into your sql table -
http://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/
Even the accepted answer is working fine. but I got this function much faster even for thousands of record. create below function and use.
IF EXISTS (
SELECT 1
FROM Information_schema.Routines
WHERE Specific_schema = 'dbo'
AND specific_name = 'FN_CSVToStringListTable'
AND Routine_Type = 'FUNCTION'
)
BEGIN
DROP FUNCTION [dbo].[FN_CSVToStringListTable]
END
GO
CREATE FUNCTION [dbo].[FN_CSVToStringListTable] (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE (Id NVARCHAR(max) NOT NULL)
AS
BEGIN
;-- Ensure input ends with comma
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%', #INSTR)
SELECT #VALUE = LEFT(#INSTR, #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab (Id)
VALUES (#VALUE)
END
RETURN
END
GO
---Test like this.
declare #v as NVARCHAR(max) = N'asdf,,as34df,234df,fs,,34v,5fghwer,56gfg,';
SELECT Id FROM dbo.FN_CSVToStringListTable(#v)
I was about you use the solution mentioned in the accepted answer, but doing more research led me to use Table Value Types:
These are far more efficient and you don't need a TVF (Table valued function) just to create a table from csv. You can use it directly in your scripts or pass that to a stored procedure as a Table Value Parameter. The Type can be created as :
CREATE TYPE [UniqueIdentifiers] AS TABLE(
[Id] [varchar](20) NOT NULL
)

How to determine internal name of table-valued variable in MS SQL Server 2005

The name of a temporary table such as #t1 can be determined using
select #TableName = [Name]
from tempdb.sys.tables
where [Object_ID] = object_id('tempDB.dbo.#t1')
How can I find the name of a table valued variable, i.e. one declared by
declare #t2 as table (a int)
the purpose is to be able to get meta-information about the table, using something like
select #Headers = dbo.Concatenate('[' + c.[Name] + ']')
from sys.all_columns c
inner join sys.tables t
on c.object_id = t.object_id
where t.name = #TableName
although for temp tables you have to look in tempdb.sys.tables instead of sys.tables. where do you look for table valued variables?
I realize now that I can't do what I wanted to do, which is write a generic function for formatting table valued variables into html tables. For starters, in sql server 2005 you can't pass table valued parameters:
http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters
moreover, in sql server 2008, the parameters have to be strongly typed, so you will always know the number and type of columns.
Table variable metadata is viewable in tempdb.sys.tables too. This is easily verifiable from the below
declare #t2 as table ( [38F055D8-25D9-4AA6-9571-F436FE] int)
SELECT t.name, t.object_id
FROM tempdb.sys.tables t
JOIN tempdb.sys.columns c
ON t.object_id = c.object_id
WHERE c.name = '38F055D8-25D9-4AA6-9571-F436FE'
Example Results
name object_id
------------------------------ -----------
#4DB4832C 1303675692
But you will notice the object name is auto generated and bears no relation to the variable name.
If you do not have a guaranteed unique column name that you can use to filter on as above and the table variable has at least one row in it you can (from SQL Server 2008 onwards) use %%physloc%% and DBCC PAGE to determine this information. Example below.
DECLARE #t2 AS TABLE ( a INT)
INSERT INTO #t2
VALUES (1)
DECLARE #DynSQL NVARCHAR(100)
SELECT TOP (1) #DynSQL = 'DBCC PAGE(2,' + CAST(file_id AS VARCHAR) + ',' +
CAST( page_id AS VARCHAR) +
',1) WITH TABLERESULTS'
FROM #t2
CROSS APPLY sys.fn_PhysLocCracker( %% physloc %% )
DECLARE #DBCCPage TABLE (
[ParentObject] [VARCHAR](100) NULL,
[Object] [VARCHAR](100) NULL,
[Field] [VARCHAR](100) NULL,
[VALUE] [VARCHAR](100) NULL )
INSERT INTO #DBCCPage
EXEC (#DynSQL)
SELECT VALUE AS object_id,
OBJECT_NAME(VALUE, 2) AS object_name
FROM #DBCCPage
WHERE Field = 'Metadata: ObjectId'
From Books Online:
A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.
Given this, there should be no need to look up this value at run-time because you have to know it at design-time.
I don't believe you can, as table variables are created in memory not in tempdb.
On the topic of passing arbitrary lists/arrays into a SQL Server 2005 function or sproc, the least hokey way I know is to use an XML variable. If desired, that XML variable can be a strongly typed XML type that is associated w/ an XML Schema.
Given a list passed into a procedure/function as XML, you can extract that list into a table variable or temp table via "shredding".
"To shred" XML means to transform in the opposite direction--from XML to rowset(s). (The FOR XML clause causes a rowset to XML transformation.)
In the user-defined table function
CREATE FUNCTION [dbo].[udtShredXmlInputBondIdList]
(
-- Add the parameters for the function here
#xmlInputBondIdList xml
)
RETURNS
#tblResults TABLE
(
-- Add the column definitions for the TABLE variable here
BondId int
)
AS
BEGIN
-- Should add a schema validation for #xmlInputIssuerIdList here
--Place validation here
-- Fill the table variable with the rows for your result set
INSERT #tblResults
SELECT
nref.value('.', 'int') as BondId
FROM
#xmlInputBondIdList.nodes('//BondID') as R(nref)
RETURN
END
if the #xmlInputBondIdList is an XML fragment of the expected structure like that immediately below and is invoked as follows
DECLARE #xmlInputBondIdList xml
SET #xmlInputBondIdList =
'<XmlInputBondIdList>
<BondID>8681</BondID>
<BondID>8680</BondID>
<BondID>8684</BondID>
</XmlInputBondIdList>
'
SELECT *
FROM [CorporateBond].[dbo].[udtShredXmlInputBondIdList]
(#xmlInputBondIdList)
the result will be the rowset
BondId
8681
8680
8684
A couple other examples can be found at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=678284&SiteID=1