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: ,

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