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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Anurag SinghPosted Mar 16, 2015, 6:18 AM
Thanks for your valuable answers.
Anurag Singh
Riddhi ValechaPosted Mar 16, 2015, 6:06 AM
You can make a function and use LISTAGG.
Call this function in your select query.
Khargesh RajputPosted Mar 16, 2015, 5:38 AM
SELECT @commavalue = COALESCE(@commavalue + ', ', '') + CAST(Name AS varchar(20)) FROM topic C
SELECT @commavalue
Manish Kumar ChoudharyPosted Mar 16, 2015, 5:24 AM
Select ',' +Name from <tableName> for XML Path(''), Type
Vikram AgrawalPosted Mar 16, 2015, 5:14 AM
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.
Joginder BangerPosted Mar 16, 2015, 2:20 AM
select STUFF((select '',''+rtrim(t.Name)from table Name t
for XML Path('''')),1,1,'''') Name,