t-sql most efficient row to column? for xml path, pivot
Posted
by ajberry
on Stack Overflow
See other posts from Stack Overflow
or by ajberry
Published on 2010-04-12T14:33:31Z
Indexed on
2010/04/12
14:43 UTC
Read the original article
Hit count: 344
create table _orders (
OrderId int identity(1,1) primary key nonclustered
,CustomerId int
)
create table _details (
DetailId int identity(1,1) primary key nonclustered
,OrderId int
,ProductId int
)
insert into _orders (CustomerId)
select 1
union select 2
union select 3
insert into _details (OrderId,ProductId)
select 1,100
union select 1,158
union select 1,234
union select 2,125
union select 3,105
union select 3,101
union select 3,212
union select 3,250
--
select orderid
,REPLACE(( SELECT ' ' + CAST(ProductId as varchar)
FROM _details d
WHERE d.OrderId = o.OrderId
ORDER BY d.OrderId,d.DetailId
FOR XML PATH('')
),' ','') as Products
from _orders o
I am looking for the most performant way to turn rows into columns. I have a requirement to output the contents of the db (not actual schema above, but concept is similar) in both fixed width and delimited formats. The above FOR XML PATH query gives me the result I want, but when dealing with anything other than small amounts of data, can take awhile.
I've looked at pivot but most of the examples I have found are aggregating information. I just to combine the child rows and tack them onto the parent.
For example, for an order it would need to output:
OrderId,Product1,Product2,Product3,etc
Thoughts or suggestions? I am using SQL Server 2k5.
© Stack Overflow or respective owner