日期:2014-05-18  浏览次数:20498 次

请教,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 @col2=@col2+ '% '+@col
insert @T(col) values(stuff(@col2, 1, 1, ' '))
set @col2= ' '
end
else
begin
set @col2=@col2+ '% '+@col
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)