5

What will be the query in MS Sql Server to concatenate my rows in one string , delimited by comma (Like shown below)

query to delimeter string

4
  • Which DBMS are you using? Oracle or SQL Server? And Have you tried something? Commented Jan 22, 2017 at 6:06
  • SQL SERVER, i have no idea how to do..... Commented Jan 22, 2017 at 6:33
  • 1
    Please have a look here stackoverflow.com/q/194852/1530987 Commented Jan 22, 2017 at 6:46
  • Please read How to Ask. Commented Jan 22, 2017 at 8:07

2 Answers 2

11

Use STUFF and FOR XML:

Create and populate sample table (Please save us this step in your future questions)

DECLARE @T AS TABLE
(
    Name varchar(10)
)

INSERT INTO @T VALUES
('John'),
('Vicky'),
('Sham'),
('Anjli'),
('Manish')

The query:

SELECT STUFF((
    SELECT ',' + Name
    FROM @T
    FOR XML PATH('')
), 1, 1, '') As [output];

Results:

output
John,Vicky,Sham,Anjli,Manish
Sign up to request clarification or add additional context in comments.

Comments

4

Assuming That your column name is NAME And table name is MYTABLE you can use the Following query:

DECLARE @strTemp VARCHAR(MAX)

SET @strTemp = ''

SELECT @strTemp  = @strTemp + ISNULL(NAME,'') + ','
FROM MYTABLE

--Remove last comma
SET @strTemp = SUBSTRING(@strTemp ,1,LEN(@strTemp ) -1)

--Get Result
SELECT @strTemp 

You can filter null records using the following

SELECT @strTemp  = @strTemp + NAME + ','
FROM MYTABLE
WHERE NAME IS NOT NULL

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.