Tuesday, February 25, 2014

selecting table columns as table rows

Hi h2007,


You can also use a SQL string split function instead of Pivot and Unpivot too.


If you check the referenced article, you will find a sample split function codes and a sample case where you can use it.


Besides, I hope following script can handle your requirement



create table companydata ( companyid smallint, valuelist nvarchar(1000))

insert into companydata select 1, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 2, '100,200,300,400,500,600,700,800,900,1000,1100,1200'
insert into companydata select 3, '101,201,301,401,501,601,701,801,901,1001,1101,1201'
insert into companydata select 4, '102,202,302,402,502,602,702,802,902,1002,1102,1202'
insert into companydata select 5, '103,203,303,403,503,603,703,803,903,1003,1103,1203'
insert into companydata select 6, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 7, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 8, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 9, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 10, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 11, '1,2,3,4,5,6,7,8,9,10,11,12'
insert into companydata select 12, '1,2,3,4,5,6,7,8,9,10,11,12'

select c.companyid, s.val
from companydata c
cross apply dbo.Split(c.valuelist,',') s





SQL Server, SQL Server 2012 Denali and T-SQL Tutorials


No comments:

Post a Comment