楼主试试用插入前触发器。如:create trigger tri_B on B instead of insert as if not exists(select a.* from a left join inserted b on a.User_ID=b.User_ID) insert into a (User_ID,update_time) select User_ID,update_time from inserted go
--哦,看错。应该改成这样。 create trigger tri_B on B for insert as if not exists(select a.* from a left join inserted b on a.User_ID=b.User_ID) insert into a (User_ID,update_time) select User_ID,update_time from inserted go
--用这个试试。 create trigger tri_B on B for insert as insert into a (User_ID,update_time) select User_ID,update_time from inserted b where not exists(select 1 from a where User_ID=b.User_ID) go
你还是把前台改成用存储过程吧 insert into b values(xx,xx) -> sp_insert_b(xx,xx),存储过程里想怎么写就怎么写!不是更方便么?
有点意思了,用这种方法可以解决我的第二次问题(前台同进插入表A和表B,但是我第1个功能有问题了,当只向表B中插入User_id时,激发触发器向表A中插入数据时,不起作用了。要执行两次才起作用。我是这样判断的。select @del_cnt=count(*) from deleted; if (select count(*) from inserted) > 0 and @del_cnt=0 begin end
同时插入的,表A和表B的Update_time时间是一模一样。微妙都一样。所以在表B中加判断是不起作用了。
楼主试试用插入前触发器。如:create trigger tri_B on B instead of insert
as
if not exists(select a.* from a left join inserted b on a.User_ID=b.User_ID)
insert into a (User_ID,update_time) select User_ID,update_time from inserted
go
--哦,看错。应该改成这样。
create trigger tri_B on B for insert
as
if not exists(select a.* from a left join inserted b on a.User_ID=b.User_ID)
insert into a (User_ID,update_time) select User_ID,update_time from inserted
go
--用这个试试。
create trigger tri_B on B for insert
as
insert into a (User_ID,update_time) select User_ID,update_time from inserted b where not exists(select 1 from a where User_ID=b.User_ID)
go
现在问题是这样的,前台(成品软件)功能需要同时往表A和表B中插入,我在触发器中加了waitfor delay '00:00:10'之后,发现前台是先向表B中插入的,再向表A中插入的。所以就算在表B的触发器中加了判断,判断结果也是在表A中没有此记录,所以触发器会向表A中插入此UserId,但是前台仍会向表A中插入,导致主键冲突。
insert into b values(xx,xx) -> sp_insert_b(xx,xx),存储过程里想怎么写就怎么写!不是更方便么?
if (select count(*) from inserted) > 0 and @del_cnt=0
begin
end
关键我所说的两个功能都是INSERT触发器啊,都是往表B里插入数据时要激发触发器。再说 if not exists(select a.* from a left join inserted b on a.User_ID=b.User_ID)这种条件好像永远都不会成立,除非表A里面是空的。