Concatenating Strings in SQL without a Loop

by Serena 28. September 2009 19:28

When you find yourself in a situation where you would like to concatenate the data items for a data object into one line, where the object can be related to many data items that are stored in a separate table, here is a quick way to accomplish that in SQL without expressly using a loop:

concatenate in SQL without loop example

  • Lines 2-3: declare and initialize variable that will be used to hold the concatenated string
  • Line 5: select variable to equal itself plus the string you are interested in and a delimiter such as a comma, if desired
  • Lines 6-9: the query that returns the data items for the object you are interested in
  • Line 11: trim off the excess delimiter from the concatenated string

The resulting concatenated string:

image

An example application is to place this type of concatenation in a function where you can submit the ID for the object you are concatenating data items for to the function, and have it return the concatenated string.

Tags: ,

Comments

1/8/2010 11:38:02 AM #

Couldn?t be written any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thanks for sharing!

Mobilt bredbånd United States |

1/9/2010 5:31:38 PM #

I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

12 bicycles United States |

Powered by BlogEngine.NET 1.5.0.7
Theme by Perkins Consulting Content Copyright 2009 Perkins Consulting, LLC All rights reserved.