4

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

Hadi
  • 36,233
  • 13
  • 65
  • 124
Ajit Kumar
  • 65
  • 1
  • 1
  • 3

2 Answers2

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
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
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
Hadi
  • 36,233
  • 13
  • 65
  • 124