2

Please check below table

Code   Name  
-----------
 001   A
 001   B

My query is

Select Code,Name from TableA

But I need records like

Code  Name
------------
001    A,B

How can I do that?

0

2 Answers 2

3

Unlike MySQL, SQL Server doesn't have a built-in function for this but you can still simulate it by using CROSS APPLY and FOR XML PATH('')

SELECT  a.Code, 
        SUBSTRING(d.[Name],1, LEN(d.[Name]) - 1) AddressList
FROM    
        (
            SELECT DISTINCT Code
            FROM TableA
        ) a
        CROSS APPLY
        (
            SELECT [Name] + ', ' 
            FROM TableA AS B 
            WHERE A.[Code] = B.[Code] 
            FOR XML PATH('')
        ) D ([Name]) ;

SQLFiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

0

You could use COALESCE. The following sample turns this

Hello

World

It's

Me

into this

Hello, World, It's, Me

DECLARE @test NVARCHAR(2000)
SELECT @test = COALESCE(@test + ', ', '') + Field FROM Sampletable WHERE … AND Field IS NOT NULL
SELECT @test

You should be able to adapt this to your sample.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.