Single column of data into multiple columns single row
I have a table that has one column. How do I write a T-SQL statement to return all the r开发者_StackOverflowows in the table as one row but a column for each row of data in the table?
you are looking for a pivot : http://msdn.microsoft.com/en-us/library/ms177410.aspx
You can do this by building a dynamic sql statement.
-- Test data
declare @T table (F varchar(10))
insert into @T values
('Row 1'),
('Row 2'),
('Row 3'),
('Row 4'),
('Row 5')
-- String to hold dynamic sql
declare @S as varchar(max)
set @S = 'select '
--Build string
select @S = @S + quotename(F, '''') + ','
from @T
set @S = left(@S, len(@s)-1)
--Execute sql
exec (@S)
Result
----- ----- ----- ----- -----
Row 1 Row 2 Row 3 Row 4 Row 5
精彩评论