if object_id('tb') is not null
drop table tb
gocreate table tb(物料名称 varchar(50),数量 int,生产单位 varchar(50))
insert into tb select 'W001',100,'A1'
insert into tb select 'W002',200,'B1'
go
create trigger tri_name
on tb
instead of update
as
begin
if update(生产单位)
update a set 生产单位=b.生产单位 from tb a inner join inserted b on a.物料名称=b.物料名称
else
begin
raiserror 50005 N'不允许修改其他列'
rollback
end
end
goupdate tb set 数量=300 where 物料名称='W001'
--消息 50005,级别 16,状态 1,过程 tri_name,第 10 行
--不允许修改其他列
--消息 3609,级别 16,状态 1,第 1 行
--事务在触发器中结束。批处理已中止。update tb set 生产单位='A3' where 物料名称='W001'
--成功
select * from tb物料名称 数量 生产单位
W001 100 A3
W002 200 B1
drop table tb
gocreate table tb(物料名称 varchar(50),数量 int,生产单位 varchar(50))
insert into tb select 'W001',100,'A1'
insert into tb select 'W002',200,'B1'
go
create trigger tri_name
on tb
instead of update
as
begin
if update(生产单位)
update a set 生产单位=b.生产单位 from tb a inner join inserted b on a.物料名称=b.物料名称
else
begin
raiserror 50005 N'不允许修改其他列'
rollback
end
end
goupdate tb set 数量=300 where 物料名称='W001'
--消息 50005,级别 16,状态 1,过程 tri_name,第 10 行
--不允许修改其他列
--消息 3609,级别 16,状态 1,第 1 行
--事务在触发器中结束。批处理已中止。update tb set 生产单位='A3' where 物料名称='W001'
--成功
select * from tb物料名称 数量 生产单位
W001 100 A3
W002 200 B1
on 表 for update
as
begin
update a
set a.[生产单位] = b.[生产单位]
from 表 a , inserted b
where a.[物料名称] = b.[物料名称]
end
for update
as
begin
if update(N'物料名称') or update(N'数量')
raiserror 99999 N'不允许 物料名称 或者 数量 列'
end
for update
asif update(N'物料名称') or update(N'数量')
begin
Rollback tran --回滚更改
--报错误信息
raiserror 99999 N'不允许 物料名称 或者 数量 列'
end
go
create table tb(f1 varchar(10),f2 int,f3 varchar(10))
go
insert tb select 'W001', 100 , 'A1'
union all select 'W002' , 200, 'B1'
go
create trigger tr
on tb
instead of update
as
if not update(f2) and not update(f3)
update a set f1=b.f1 from tb a
inner join inserted b
on a.f2=b.f2 and a.f3=b.f3
goupdate tb set f1='aaa'
select * from tb
/*changed
aaa 100 A1
aaa 200 B1*/
update tb set f2=12313
select * from tb
/*no change
aaa 100 A1
aaa 200 B1*/
W001 100 A3
W002 200 B1
create trigger tri_name
on tb
for update
as
begin
if exists(select 1 from inserted where [物料名称]<>'w001')
begin
Rollback tran
raiserror 99999 N'只允许更改 w001 的数据'
end
end
go