当前位置: 代码迷 >> Sql Server >> 请问,SQL中数据合并有关问题
  详细解决方案

请问,SQL中数据合并有关问题

热度:20   发布时间:2016-04-27 16:43:20.0
请教,SQL中数据合并问题
由于数据量比较大,条数上万,列数20左右,我将所有的列属性设置为vchar(255),现在要合并所有数据,每列用&分割,合并为1列(该列属性为vchar(MAX)),再将每100行,用%分割,请教方法!!
我现在实现了列,但是行的合并不会。。。

------解决方案--------------------
行的合并,建议用游标
------解决方案--------------------

create table T(col varchar(10))
insert T select 'A '
union all select 'B '
union all select 'C '
union all select 'D '
union all select 'E '

union all select 'F '
union all select 'G '
union all select 'H '
union all select 'I '
union all select 'J '

union all select 'K '


select id=identity(int, 1, 1), * into #T
from T

declare cur cursor for
select id, col from #T

declare @T table(col varchar(1000))
declare @id int, @col varchar(10), @col2 varchar(1000)
set @col2= ' '

open cur
fetch next from cur into @id, @col
while @@fetch_status=0
begin
if @id%5=0
begin
set @[email protected]+ '% '[email protected]
insert @T(col) values(stuff(@col2, 1, 1, ' '))
set @col2= ' '
end
else
begin
set @[email protected]+ '% '[email protected]
end
fetch next from cur into @id, @col
end
insert @T(col) values(stuff(@col2, 1, 1, ' '))
close cur
deallocate cur

select * from @T

--result
col
----------------------
A%B%C%D%E
F%G%H%I%J
K

(3 row(s) affected)
  相关解决方案