Professional Documents
Culture Documents
SQL For XML
SQL For XML
SQL For XML
net/post/5334646215/get-a-comma-separated-list-of-values-in-sql-with
As this came up a lot, we wrote a CLR function in C#, imported this into SQL Server and created a
User Defined Function (UDF) to ease concatenation of string values from rows in a table. I had a few
major problems with this approach:
1.
The code is unnecessarily complex for such a simple requirement, mainly due to the
plumbing code required to make SQL CLR functions
2.
We now have to add another process to our deployment, installing this CLR function in SQL
Server
3.
People now have to know how to do this. This is a problem - how often do you actually write
CLR functions and reference them in SQL??
I was overjoyed to find a way of achieving this that is more efficient and involves purely SQL! In can
be achieved using the SQL STUFF statement, and SQL Servers built-in XML capabilities.
Say I have the following tables (very simplistic):
CREATE TABLE [dbo].[Product](
[ProductId] [bigint] NOT NULL,
[Name] [varchar](255) NOT NULL
)
CREATE TABLE [dbo].[ModelProductFits](
[ProductId] [bigint] NOT NULL,
[ModelThisFits] [varchar](50) NOT NULL,
)
With the following values:
----------------------------| ProductId | ModelThisFits |
|---------------------------|
| 12345
| A3666
|
| 12345
| A3667
|
| 12345
| A8999
|
----------------------------And I want to output the following:
----------------------------------| ProductId | Models
|
|---------------------------------|
| 12345
| A3666,A3667,A8999
|
-----------------------------------
SELECT Item,STUFF
(
(SELECT ',' + Color
FROM [dbo].[Inventory2]
ORDER BY Color
FOR XML PATH('')),1,1,'') AS CSV
FROM [dbo].[Inventory2]