Pankajmittal’s Blog

October 7, 2011

Get Comma Separated values from table without using Function

Filed under: SQL tips — pankajmittal @ 6:00 am

Hi

Many times you come across a situation where you have to convert values stored in multiple rows in a comma separated string e.g. Part consumed in a job.

Using Coalesce you can achieve the same but the drawback is that it would hit the performance significantly if you need to call this function for each row in a recordset. Actually using any function when it needs to be applied to each row will hit query performance unless the rows returned are not too many !

As an alternate to Coalesce, you can use For XML construct which will give better performance if your recordset is large.

Sample :

SELECT t1.ID ,

SUBSTRING(( SELECT ( ‘ ,’ + t2.Part )

FROM dbo.PartConsumed t2

WHERE t1.ID = t2.ID

FOR

XML PATH(”)

), 3, 500) AS PartUsed

FROM dbo.PartConsumed t1

GROUP BY t1.ID

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.