解决通过identity字段关联的多个数据表插入问题

在数据库设计中经常要用到自动增长字段(identity) ,在使用自动增长字段做多表关联时

往往会遇到这样一个问题,当向主表插入数据后同时需要向与之关联的表插入相关的数据

比如用户基本信息表记录用户基本信息,它通过自动增长字段UserId和用户扩展信息表关联。

当向用户基本信息表插入一条用户信息后,我们需要同时向用户扩展信息表插入于这个用户相关

的扩展信息,由于我们无法知道刚被插入的这条用户基本信息对应的UserId值具体是多少,这样

在插入扩展信息表时就无法填入该值。

本文提供了一种通过触发器来解决该问题的方法,供大家参考

if exists (select * from sysobjects where id = object_id('testfk') and type = 'u')
 drop table testfk
GO
if exists (select * from sysobjects where id = object_id('testpk') and type = 'u')
 drop table testpk
GO
create table testpk
(
 id int IDENTITY(1,1)  NOT NULL PRIMARY KEY,
 a  int
)
GO
create table testfk
(
 id int FOREIGN KEY REFERENCES  testpk(id),
 b  int
)

GO
if exists (select * from sysobjects where id = object_id('testview') and type = 'v')
 drop view testview
GO
create view testview as
select testpk.id, a, b from testpk,testfk where testpk.id = testfk.id

GO
if exists (select * from sysobjects where id = object_id('InsertTowTable') and type = 'p')
 drop procedure InsertTowTable
GO

create procedure InsertTowTable
@a  int, -- a
@b int -- b
as
declare
@fid int

begin try
drop table #TEMPTABLE
end try
begin catch
end  catch

create table #TEMPTABLE
(
   id int
)

insert testpk values(@a)
select @fid = max(id) from #TEMPTABLE
insert testfk values(@fid,@b)

GO
if exists (select * from sysobjects where id = object_id('TestInsert') and type = 'p')
 drop procedure TestInsert
GO

create procedure TestInsert
@a int, -- a
@b int, -- b
@cnt int -- count
as
declare
@i int
select @i = 0
while @i < @cnt
begin
EXEC InsertTowTable @a, @b
select @i = @i+1
end
GO


if exists (select * from sysobjects where id = object_id('Insert_testpk') and type = 't')
 drop trigger Insert_testpk
GO
Create Trigger Insert_testpk On testpk
For Insert
As
Insert #TEMPTABLE(ID) Select ID From Inserted
GO

 

eaglet

2007-4-20

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值