SQL: CSV To Table using xml
Disclaimer: This is a prehistoric post , moved as is (with minor formatting change) from my old blog.
In this article I’m going to discuss about how to convert a comma separated string to a table to enable it for set based operation. Lets say we’ve a table which has the definition like this :
Problem Statement
You need to retrieve Employee Name based on EmpId provided. Now it is easier to retrieve the data when you have the EmpIds separately and the same can be used as below :
The above query treats every EmpId separately. Now what if you get all the EmpIds in a single comma separated string like : '10,21,32,43,54,74,78,47,56,12,68,'
. In that case you cannot write query as below:
The above query will not treat the EmpIds separately, but as a single csv string as a result this query will produce an erroneous result or may not parsed at all.
Solution
Now to process the csv effectively (so that it can be used for set based operation) we need to convert this csv to a table (set). You need to create the below procedure for the same.
Usage:
OUTPUT:
SerialNo | VAL |
---|---|
1 | 10 |
2 | 21 |
3 | 32 |
4 | 43 |
5 | 54 |
6 | 74 |
7 | 78 |
8 | 47 |
9 | 56 |
10 | 12 |
11 | 68 |
The above table variable can also be used as below :
Explanation
Our Stored procedure csvToTable_xml
accepts two parameters: @csv
& @Delimiter
. @csv
contains the delimited string. @Delimiter
contains the delimiter, yes you’ve guessed right, you can use not only comma but any delimiter as you like. Now the idea is to convert this csv to xml something like this :
Now from this xml we can easily produce a record set using standard xml functions provided by MSSQL (which we’re not going to discuss in this article as it is out of scope).
Hope this helps.