34,871
社区成员




--更新触发器
create trigger tupdate_sales on sales
for update
as
begin
--更新指定的字段不执行
if update(a) and update(b)
and exists(select 1 from inserted i,deleted d where i.id = d.id
and i.a <> d.a
and i.b <> d.b)
begin
return
end
--更改价格,更新价格表
if update(price) and exists(select 1 from prices,inserted i,deleted d
where i.id = d.id
and prices.item_code = i.item_code
)
begin
--存在时更新
update prices
set price = i.price
from inserted i,deleted d
where prices.item_code = i.item_code
and i.id = d.id
and i.price <> d.price
end
else
begin
insert into prices(item_code,price)
select i.price,i.item_code
from inserted i
where not exists(select 1 from prices where prices.item_code = i.item_code)
end
end
销售表sales,主键:id,与价格表关联:item_code
价格表prices
--插入触发器
create trigger tinsert_sales on sales
for insert
as
begin
if exists(select 1 from prices where prices.item_code = inserted.item_code)
begin
--存在时更新
update prices
set price = i.price
from inserted
where prices.item_code = inserted.item_code
end
else
begin
insert into prices(item_code,price)
select i.price,i.item_code
from inserted i
where not exists(select 1 from prices where prices.item_code = i.item_code)
end
end
--更新触发器
create trigger tupdate_sales on sales
for update
as
begin
--更新指定的字段不执行
if update(a) and update(b)
and exists(select 1 from inserted i,deleted d where i.id = d.id
and i.a <> d.a
and i.b <> d.b)
begin
return
end
--更改价格,更新价格表
if update(price) and exists(select 1 from prices where prices.item_code = inserted.item_code)
begin
--存在时更新
update prices
set price = i.price
from inserted i,deleted d
where prices.item_code = i.item_code
and i.id = d.id
and i.price <> d.price
end
else
begin
insert into prices(item_code,price)
select i.price,i.item_code
from inserted i
where not exists(select 1 from prices where prices.item_code = i.item_code)
end
end
create trigger tb_twocolumnupdate
on 销售表
after update
as
begin
if update(A) and update(B) --当销售表中的两个字段同时修改时,不更新价格表
begin
rollback
end
else
begin
update 价格表....
end
end
create table tb
(
ID int identity(1,1),
A varchar(10),
B varchar(10),
C varchar(10)
)
insert into tb
select 'a1','b1','c1' union all
select 'a2','b2','c2'
create trigger tb_twocolumnupdate
on tb
after update
as
begin
if update(A) and update(B) --AND 或者 OR 看你的需求
rollback
end
update tb set A='1111' where ID=1
(1 行受影响)
update tb set A='1111',B='2222' where ID=1
事务在触发器中结束。批处理已中止。
create table tb
(
ID int identity(1,1),
A varchar(10),
B varchar(10),
C varchar(10)
)
insert into tb
select 'a1','b1','c1' union all
select 'a2','b2','c2'
create trigger tb_twocolumnupdate
on tb
after update
as
begin
if update(A) or update(B)
rollback
end
update tb set A='1111' where ID=1
事务在触发器中结束。批处理已中止。