Wednesday, August 14, 2013

Multiple Rows to Single Row in SQL

 

Using SQL you can convert multiple rows to single row with any separator.

In the below example there is a table having data in 5 rows.

SELECT VALUE FROM TableName

Out Put is


VALUE
112
114
115
126
127


User wants to convert these 5 rows to a single row with all data departed by comma.

DECLARE @Names VARCHAR(8000) 

SELECT @Names = COALESCE(@Names + ', ', '') + cast(Value as varchar(100)) FROM TableName

SELECT @Names

Out Put is


112, 114, 115, 126, 127

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.