Tips in T-SQL
This page is a reminder and how-to for my best tips in TSQL
Insert an xml ID list into a table
A method to convert an xml formatted ID list into a resultset. Very useful to pass lists from a client to a SP.
From the table below we want to extract a set or record whose IDAnag is passed by in an xml parameter.
First we have to split the parameter (@Lista) so it's possible to join the result with the table.
Table Anagrafiche
| IDAnag |
FirstName |
Surname |
| 1 |
Mauro |
Rossi |
| 2 |
Simone |
Casara |
| 4 |
Alessandro |
Chiappin |
| 6 |
Alessio |
Trevisan |
| 7 |
Francesco |
Sartor |
DECLARE @Lista xml
SET @Lista = '<list><id>2</id><id>7</id></list>'
SELECT idAnag.value('.', 'int')
FROM @Lista.nodes('/list/id') AS TableRet(idAnag) |
The resultset is composed of one unnamed column which could be joined with the table Anagrafiche.
The core of the method is the xpath query /list/id which is applied to the xml variable @Lista through its method nodes.
The xml string has to respect the expected schema (/list/id).