日期:2014-05-17  浏览次数:20421 次

关于一个触发器的问题
假如现在又两个表 A                  B        
a1    a2     a3                     b1     b2     b3
1      2      3                     4      5      6
7      8      9                     3      8      9
现在我想写一个触发器,该触发器的功能是:往A表中的a1字段插入一个值,如果插入的数值跟B表中的b1值相等,那么就把B表中的b2值赋给A表中的a2值,此时A表增加一条新的记录。否则,什么也不做。
例如,我往A表中a1字段插入一个3,,那么就把b2=8赋值给a2,此时A表更新为
a1   a2   a3
1    2     3
7    8     9
3    8
请问该怎么写?各位大侠赐教!!

------解决方案--------------------
declare @b1 int
declare @b2 int
declare @n int
set @n=0
set @b2=0 --如果是字值可设置为空
select @b1=a1 from inserted

select @n=count(*) from b where b1=@b1
if @n>0
begin
  select @b2=b2 from b where b1=@b1
  update a set a2=@b2 where a1=@b1
end
else
begin
  delete a where a1=@b1
end
------解决方案--------------------
create TRIGGER trg_test ON A
AFTER INSERT
AS
begin 
IF EXISTS(SELECT 1 FROM B INNER JOIN INSERTED T ON B.b1 = T.a1)
INSERT INTO a(a1,a2)
SELECT T.a1,B.b2
FROM B 
INNER JOIN  INSERTED T ON B.b1 = T.a1
END