How to format TSQL SELECT output in SQL Sever
3 answers
If the table contains multiple records, that is:
1, name1, .. 2, name2, .. 3, name3, ..
then this query:
DECLARE @names VARCHAR(MAX)
SELECT @names = COALESCE(@names + ', ', '') + name
FROM table
will produce the following result:
name1, name2, name3
See COALESCE on MSDN
+5
a source to share
If you plan to do a function that you do on each line, form a different request, it will be very slow because the function must be called on each line. You have to work with datasets in one go, it executes all rows in one go. This is an example of how to concatenate multiple values for each line of a different query:
set nocount on;
declare @t table (id int, name varchar(20), x char(1))
insert into @t (id, name, x)
select 1,'test1', 'a' union
select 1,'test1', 'b' union
select 1,'test1', 'c' union
select 2,'test2', 'a' union
select 2,'test2', 'c' union
select 3,'test3', 'b' union
select 3,'test3', 'c'
SELECT p1.id, p1.name,
stuff(
(SELECT
', ' + x
FROM @t p2
WHERE p2.id=p1.id
ORDER BY name, x
FOR XML PATH('')
)
,1,2, ''
) AS p3
FROM @t p1
GROUP BY
id, name
OUTPUT:
id name p3
----------- -------------------- -----------
1 test1 a, b, c
2 test2 a, c
3 test3 b, c
+1
a source to share