0

Anyone can help please I want to Convert sql table column to a comma separated row in azure sql I have already tried this code but getting error that can not convert to varchar please suggest

DECLARE @Country TABLE (id INT, [Name] Varchar(30) )

INSERT INTO @Country VALUES (1,'India')
INSERT INTO @Country VALUES (2,'USA')
INSERT INTO @Country VALUES (3,'Japan')
INSERT INTO @Country VALUES (4,'China')
INSERT INTO @Country VALUES (5,'Switzerland')

SELECT STUFF( -- Remove first comma
(SELECT  ', ' + ID FROM -- create comma separated values
(SELECT ID FROM @Country --Your query here
) AS T FOR XML PATH('')
)
,1,1,'') AS [Name]
0

2 Answers 2

1

You could use STRING_AGG:

SELECT STRING_AGG(ID, ', ') FROM @Country

db<>fiddle demo

XML + STUFF is old way when there was no GROUP_CONCAT equivalent available.

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

Comments

1

You need CAST the integer

SELECT  ', ' + CAST(ID as nvarchar(max)) FROM

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.