I have a table in SQL and table has one column(NAME) and the values are in NAME column as
A
B
C
...
...
...
X
Y
Z
Then, I want to show data through SQL query in a single line like A, B, C, ..... X, Y, Z.
Anurag Singh
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Joginder BangerRank #360 · 7K reputationPosted Mar 15, 2015, 10:20 PM EDT
select STUFF((select '',''+rtrim(t.Name)from table Name t
for XML Path('''')),1,1,'''') Name,
Vikram AgrawalRank #4,713 · 329 reputationPosted Mar 16, 2015, 1:14 AM EDT
you can accomplish your requirement by creating one Stored Procedure.
see below for SP
CREATE PROCEDURE GetSepratedValue
(
@TableName Varchar(100), @ColumnName Varchar(100), @Delimeter Char(1)
)
AS
BEGIN
DECLARE @TEMP TABLE (ID INT IDENTITY,MYCOLUMN VARCHAR(200) )
DECLARE @TotRows INT
DECLARE @Result Varchar(MAX)=''
INSERT INTO @TEMP (MYCOLUMN)
EXEC (N'SELECT ' + @ColumnName + ' FROM ' + @TableName)
SET @TotRows = @@ROWCOUNT
DECLARE @MIN INT = 1
WHILE(@MIN < @TotRows)
BEGIN
SELECT @RESULT = @RESULT + MYCOLUMN + ',' FROM @TEMP WHERE ID = @MIN
SET @MIN +=1
END
SELECT SUBSTRING(@Result,1,LEN(@RESULT)-1)
END
-- EXEC GetSepratedValue 'TestTable', 'TestColumn', ','
Thanks.
Manish Kumar ChoudharyRank #339 · 7.4K reputationPosted Mar 16, 2015, 1:24 AM EDT
Select ',' +Name from <tableName> for XML Path(''), Type
Khargesh RajputRank #616 · 3.9K reputationPosted Mar 16, 2015, 1:38 AM EDT
SELECT @commavalue = COALESCE(@commavalue + ', ', '') + CAST(Name AS varchar(20)) FROM topic C
SELECT @commavalue
Riddhi ValechaRank #794 · 2.9K reputationPosted Mar 16, 2015, 2:06 AM EDT
You can make a function and use LISTAGG.
Call this function in your select query.
Anurag Singh131 reputationPosted Mar 16, 2015, 2:18 AM EDT
Thanks for your valuable answers.
Anurag Singh