Concatenate Column Values from Multiple Rows into a Single Column in SQL Server

October 11, 2007 11:46 by Dominick

What I needed to happen


There is likely many other more efficient ways to accomplish this, but this is the way I figured out how to do it in my particular situation. I needed to be able to combine column values in a table into a single column to be able to do a filter or search. I'll show you what I mean.

First Table 

 

RecordIdName
1001Sandy
1002Tom
1003Jim

Second Table

This table stores multiple records for each person.

RecordIdFieldtoConcat
10011
10012
10021
10023
10031
10032
10033


I needed to have this data set returned so I could then filter the list by search for each "FieldtoConcat" in the list.

RecordIdNameConcatedFields
1001Sandy^1^^2^
1002Tom^1^^3^
1003Jim^1^^2^^3^


The first question you may ask is what's up with the "^". Its a simple reason. If there were any records with a value of, say, "10" when I would search for just "1" then I would get all the records that had "1" in them. So my solution was to search for "^1^" which would ensure that I would only get the desired records.

How to do it


To pull this off you need to create a function. Here it is:

CREATE FUNCTION [dbo].[ConcatField](@RecordId int)
RETURNS VARCHAR(1000)
AS
BEGIN
    DECLARE @ReturnValue VARCHAR(1000)
    SET @ReturnValue = ''

    SELECT @ReturnValue =    CASE @ReturnValue
                WHEN '' THEN '^' + CAST(FieldtoConcat AS VARCHAR(3)) + '^'
                ELSE @ReturnValue + '^' + CAST(FieldtoConcat AS VARCHAR(3)) + '^' 
                END
    FROM TableWithTheFieldtoConcat
    WHERE Id = @RecordId
    ORDER BY FieldtoConcat

    RETURN @ReturnValue
END


It takes the RecordId as a parameter, combines all the numbers into @ReturnValue and returns the values as desired.

After that it gets easy.  I'll just show you the SQL because it's pretty self explanatory.

SELECT     RecordId, Name, CAST(ConcatField(RecordId) AS VARCHAR(1000)) AS ConcatedFields
FROM         FirstTable


You can insert a "WHERE ConcatedFields LIKE %^1^%" and it will only pull the records with "1". That's all there is to it. Anybody have a better way? Please comment.



kick it on DotNetKicks.com

Technorati Profile

Tags:
Categories: SQL | General
Actions: E-mail | Permalink | Comments (6) | Comment RSSRSS comment feed


Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading