Friday, December 14, 2012

Comma Separated string in Sql Server using XPATH


We have the below table.

number
2
10


Expected out put:

ItemList
2, 10

We can use XML Xpath expression in our select query to get the above result.

select ItemList = substring((select(', '+CONVERT(varchar,number)) from tbltest
FOR XML PATH( '' )),2,100)

substring()
Expects three parameters
SUBSTRING ( expression ,start , length )

expression
Is a character, binary, text, ntext, or image expression.

start
Is an integer or bigint expression that specifies where the returned characters start.

length
Is a positive integer or bigint expression that specifies how many characters of the expression will be returned.

FOR XML PATH
TYPE to create a typed XML value (as opposed to a string containing xml). An XML typed subquery will create an XML element, a string will just insert the result as text() and will be escaped.

No comments:
Write comments
Recommended Posts × +