CREATE TABLE #test
(
ID INT IDENTITY,
NAME VARCHAR(50)
)
INSERT INTO #test(NAME) VALUES ('Ram')
INSERT INTO #test(NAME) VALUES ('Shyam')
INSERT INTO #test(NAME) VALUES ('Ghanshyam')
INSERT INTO #test(NAME) VALUES ('Krishna')
SELECT * FROM #test
ID
|
NAME
|
1
|
Ram
|
2
|
Shyam
|
3
|
Ghanshyam
|
4
|
Krishna
|
SELECT STUFF((SELECT ',' + NAME FROM #test t FOR XML PATH('')),1,1,' ') AS 'OUTPUT'
OUTPUT
|
Ram,Shyam,Ghanshyam,Krishna
|
OR
DECLARE @NameList varchar(MAX)
SELECT @NameList = COALESCE(@NameList + ',', '') +
CAST(NAME AS VARCHAR(MAX))
FROM #test
SELECT @NameList AS 'OUTPUT'
OUTPUT
|
Ram,Shyam,Ghanshyam,Krishna
|
NOTE:-
STUFF is combination of
STUFF = SUBSTRING + REPLACE
No comments:
Post a Comment