求一条循环my SQL查询 插入语句

来源:百度知道 编辑:UC知道 时间:2024/06/05 03:16:05
两个表
表1
aid tag
1 文字1
1 文字2
1 文字3
2 文字5
2 文字6
2 文字7
表2 id为主键
id keywords
1
2
3
实现结果在表2里面
id keywords
1 文字1,文字2,文字3

ALTER PROCEDURE p_test AS

declare @tags varchar(10)
declare @ret varchar(50)
declare @aid int
declare cur_aid cursor for select distinct aid from dedejcw_taglist

open cur_aid
fetch next from cur_aid into @aid
while @@fetch_status = 0
begin
set @ret = ''
declare cur_tags cursor for select tags from dedejcw_taglist where aid = @aid
open cur_tags
fetch next from cur_tags into @tags
while @@fetch_status = 0
begin
set @ret = @ret +@tags + ','
fetch next from cur_tags into @tags
end
close cur_tags
deallocate cur_tags

insert into test values(@aid,substring(@ret,1,len(@ret)-1))
fetch next from cur_aid into @aid
end
close cur_aid
deallocate cur_aid
GO
--执行
exec p_test
--结果select * from test
id keywords
1 文字1,文字2,文字3
2 文字5,文字6,文字7

如果是楼主这样的话,那表二就完全没有必要创建了,可以使用视图代替。