Blogs

Tuesday, June 12, 2012

T-SQL : Column to Comma separated string


We often get into the problem of getting a particular column value as a comma separated string in SQL. I don’t know how many of you have faced this problem, but in my case, it is many a times. Hence I decided to blog here !!! :)

Let’s say I have the following Query with the given result:

SELECT AlarmTypeID FROM AlarmType




















Now, we need to get the comma separated value for the column AlarmTypeID.
This can be done with the below mentioned query:

SELECT AlarmTypeID = STUFF((SELECT ',' + CONVERT(VARCHAR,AlarmTypeID) 
FROM AlarmType FOR XML PATH('')), 1,1, ' ')

When you run the above query, you would get the result like shown below:




No comments:

Post a Comment

Please leave your words here !