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

触发器的简单应用
需求:表A,有两个字段ID,a;某一条记录有update操作时,如果其字段a>10,则把这条记录插入到B表中(B中也有ID这个字段,如果已经存在这个ID的了,则不执行插入操作,否则执行)
------最佳解决方案--------------------
create trigger triTest
on A
for update
as
begin
  insert b
  select xxx,xxx from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10
end
------其他解决方案--------------------
create trigger triTest
on A
for update
as
begin
  if (updated.a>10) and updated.ID not in(select ID from b)
  begin
    insert b values(getdate(),updated.ID,a)
  end
end

这是我查了触发器基本语法后,写的一个很挫的sql语句。。。显然用不了。。。希望高人不吝指点。。。
------其他解决方案--------------------
引用:
create trigger triTest
on A
for update
as
begin
  insert b
  select xxx,xxx from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10
end

想问下,select xxx,xxx from inserted a,这句怎么理解呢?
可能我没有说清楚,b表的字段跟a表的字段并不完全一样。。。
------其他解决方案--------------------
create trigger triTest
on A
for update
as
begin
  insert b
  values(getdate(),
  select id from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10,'修改')
end
我现在改成了这样,但是结果不对,当a.id<=10的update时,仍然会执行插入操作,只是b表中的id为空而已
------其他解决方案--------------------
引用:
引用:create trigger triTest
on A
for update
as
begin
  insert b
  select xxx,xxx from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10……

所以让你自己定义xxx字段
------其他解决方案--------------------
引用:
create trigger triTest
on A
for update
as
begin
  insert b
  values(getdate(),
  select id from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10,'……


create trigger triTest
on A
for update
as
begin
  insert b
  select getdate(),id,'修改' from inserted a
  where not exists(select * from b b where a.id=b.id)
    and a.id>10
end

------其他解决方案--------------------
CSDN解决问题就是快,呵呵,结贴给分啦