CTE - , . , - , .
declare @texts table (
ID int not null primary key
, Col0 varchar(10) null
, Col1 varchar(10) null
, Col2 varchar(10) null
, Col3 varchar(10) null
, Col4 varchar(10) null
, Col5 varchar(10) null
, Col6 varchar(10) null
, Col7 varchar(10) null
, Col8 varchar(10) null
, Col9 varchar(10) null
)
insert into @texts select 59, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'text1'
insert into @texts select 185, NULL, NULL, NULL, NULL, NULL, 'text1', 'text2', 'text3', 'text4', 'text5'
insert into @texts select 428, NULL, NULL, NULL, NULL, NULL, NULL, 'text1', 'text2', 'text3', 'text4'
insert into @texts select 53, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'text1', 'text2'
insert into @texts select 452, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'text1'
insert into @texts select 267, 'text1', 'text2', 'text3', 'text4', 'text5', 'text6', 'text7', 'text8', 'text9', 'text10'
;with cte as (
select *
, row_number() over (partition by ID order by Col) - 1 as NewCol
from (
select ID, 0 as Col
, (select Col0 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 1 as Col
, (select Col1 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 2 as Col
, (select Col2 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 3 as Col
, (select Col3 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 4 as Col
, (select Col4 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 5 as Col
, (select Col5 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 6 as Col
, (select Col6 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 7 as Col
, (select Col7 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 8 as Col
, (select Col8 from @texts where ID = a.ID) as Val
from @texts a
union all
select ID, 9 as Col
, (select Col9 from @texts where ID = a.ID) as Val
from @texts a
) as b
where b.Val is not null
)
select ID
, (select Val from cte where ID = a.ID and NewCol = 0) as Col0
, (select Val from cte where ID = a.ID and NewCol = 1) as Col1
, (select Val from cte where ID = a.ID and NewCol = 2) as Col2
, (select Val from cte where ID = a.ID and NewCol = 3) as Col3
, (select Val from cte where ID = a.ID and NewCol = 4) as Col4
, (select Val from cte where ID = a.ID and NewCol = 5) as Col5
, (select Val from cte where ID = a.ID and NewCol = 6) as Col6
, (select Val from cte where ID = a.ID and NewCol = 7) as Col7
, (select Val from cte where ID = a.ID and NewCol = 8) as Col8
, (select Val from cte where ID = a.ID and NewCol = 9) as Col9
from cte a
group by ID
order by ID