存储过程循环从一个表取数据插入到其他n个表怎么解决
我想用存储过程实现从表A:id(自增),name,add,tell中取出全部记录(不包括id)插入到表B:id(自增),name_id,add,tell中,并由表C:id(自增),name。当取出一条A的记录时判断name是否在C中存在,若存在,获取C.id并插入到B中,若不存在则将name插入到C中并获取该name的id连同A中其他字段插入到B中。
请高人指点
------解决方案-------------------- create table A(id int identity(1, 1), name varchar(10), [add] varchar(10), tell varchar(10))
go
create table B(id int identity(1, 1), name_id int, [add] varchar(10), tell varchar(10))
go
create table C(id int identity(1, 1), name varchar(10))
go
declare cur cursor local
for
select name, [add], tell from A
declare @name varchar(10), @add varchar(10), @tell varchar(10)
open cur
fetch next from cur into @name, @add, @tell
while @@fetch_status=0
begin
declare @name_id int
select @name_id=id from C where name=@name
if @name_id is null
begin
insert C(name) values(@name)
set @name_id=@@identity
end
insert B(name_id, [add], tell)
values(@name_id, @add, @tell)
fetch next from cur into @name, @add, @tell
end
close cur
deallocate cur
------解决方案--------------------用游标处理:
declare @id int,@name varchar(20),add varchar(100),tell varchar(100)
declare cursor cur for
select name,add,tell from ta
open cur
fetch next from cur into @id,@name,@add,@tell
if @@fetch_status=0
BEGIN
if not exists(select 1 from tc where name=@name)
BEGIN
insert into tc(name,add,tell) values(@name,@add,@tell)
--tc中字段id是主键,且自增
select @id=@@identity
insert into tb values(@id,@name,@add,@tell)
END
else
BEGIN
select @id=id from tc where name=@name
insert into tb values(@id,@name,@add,@tell)
END
END
close cur
deallocate cur
------解决方案--------------------不需要用游标,两条SQL语句应该足够解决问题:
------------------------------------------------
--将A表中name不存在于C表的数据insert到C表中
insert into C(name)
select name from A where not exists(select 1 from C where name=A.name)
--将A、C表中的数据insert到B表中
insert into B(name_id,add,tell)
select C.id,A.add,A.tell from A,C where A.name=C.name