主表中id 為自增列嗎?
在存儲過程 中這樣寫--插入主表
insert into 主表
select @a1,@a2--插入明細表
insert into 明細表(b1,b2)
select @b1,@b2--插入主鍵
update 明細表
set t_id=a.id
from 主表 a
where a.a1=@a1 and a.a2=@a2
在存儲過程 中這樣寫--插入主表
insert into 主表
select @a1,@a2--插入明細表
insert into 明細表(b1,b2)
select @b1,@b2--插入主鍵
update 明細表
set t_id=a.id
from 主表 a
where a.a1=@a1 and a.a2=@a2
create table 明细表(t_id int, b1 varchar(50), b2 varchar(50))
------------------------------------------------上为测试表
create proc proc_test @a1 int,@a2 varchar(50),@b1 varchar(1000),@b2 varchar(1000) as
declare @i int,@j1 varchar(1000),@j2 varchar(1000)
insert test(a1,a2) select @a1,@a2
select @i=SCOPE_IDENTITY(),@j1=@b1,@j2=@b2
while charindex(',',@j1)>0
begin
insert 明细表 select @i,left(@j1,charindex(',',@j1)-1),left(@j2,charindex(',',@j2)-1)
select @j1=stuff(@j1,1,charindex(',',@j1),''),@j2=stuff(@j2,1,charindex(',',@j2),'')
end
-------------------------------下为调用
exec proc_test 2,'采购名称','冰箱,电脑,','001,002,'
select * from test select * from 明细表
id a1 a2
----------- ----------- ----------
1 2 采购名称
(所影响的行数为 1 行)t_id b1 b2
----------- -------- ---------
1 冰箱 001
1 电脑 002(所影响的行数为 2 行)