日期:2014-05-17 浏览次数:20534 次
if object_id('test') is not null drop table test
create table test(id int,aid int,itemid int)
insert into test select 2,3,111
union all
select 4,3,222
union all
select 6,4,333
union all
select 7,3,666
declare @t1 table(aid int,content nvarchar(100))
declare @aid int
declare test_add cursor for select aid from test group by aid
open test_add
fetch next from test_add into @aid
while @@fetch_status=0
begin
declare @t nvarchar(100)
select @t=isnull(@t,'')+','+cast(itemid as varchar(30)) from test where aid=@aid
insert @t1 select @aid,stuff(@t,1,1,'')
set @t=''
fetch next from test_add into @aid
end
close test_add
deallocate test_add
select * from @t1
insert into newtb
select
aid,itemIds=stuff((select ','+ltrim([itemId]) from oldtb where aid=t.aid for xml path('')), 1, 1, '')
from oldtb t
group by aid
create table oldtb
(id int,aid int,itemid int)
insert into oldtb
select 2,3,111 union all
select 4,3,222 union all
select 6,4,333 union all
select 7,3,666
create table newtb
(aid int,itemIds varchar(20))
insert into newtb(aid,itemIds)
select a.aid,
stuff((select ','+rtrim(b.itemid)
from oldtb b
where b.aid=a.aid
for xml path('')),1,1,'')
from oldtb a
group by a.aid
select * from newtb