怎么样写这样的update触发器,求救!

blueyexin 2006-03-10 09:29:56
在一个表里面有列a,只能是有0,04,10三个值
我现在想写一个这样的触发器,当修改列a时,如果当前行列a的值是10,就报错误。
在触发器里面应该怎么知道当前要修改的是哪一行呢,困扰好多天了,请大家多多指教!
...全文
161 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wgsasd311 2006-03-10
  • 打赏
  • 举报
回复
create table test(a int,b int)
insert into test
select 0,1
union select 4,2
union select 10,3
go
create trigger tu_test on test
for update
as
if exists(select 1 from deleted t1,inserted t2 where t1.a<>t2.a and t1.a=10)
begin
rollback
raiserror ('不能修改a=10的值',16,1)
end
go
--test

update test set a=1 where a=0

update test set b=111 where a=10

update test set a=1 where a=10
select * from test
--
drop table test
blueyexin 2006-03-10
  • 打赏
  • 举报
回复
create table Test
(
a varchar(10),
b varchar(10)
)

insert into Test(a,b) values('01','10')

insert into Test(a,b) values('02','04')

create trigger Tr_Test on Test for update
as
begin
if(update(b))
if exists(select 1 from deleted where b='10')
raiserror 50001 '不能修改10为4'
end

update test set b='04' where a='01'
多谢兄弟们的指点,已经写出来了,谢谢大家!
zlp321002 2006-03-10
  • 打赏
  • 举报
回复
--测试环境
Create table T_Table( id int identity(1,1),a varchar(10))
insert into T_Table select '0'
union all select '04'
union all select '10'
--触发器
Create Trigger T_T_Table on T_Table
for update
as
begin
if update(a)
begin
if (select A.a from T_Table A inner join deleted D on A.id=D.ID)='10'
begin
print '修改错误'
rollback
end
end
end

--测试
update T_table set a='10'
where id=1
--显示结果
/*
修改错误
*/
--查看原表数据(未进行更新)
select * from T_table
/*
id a
----------- ----------
1 0
2 04
3 10

(所影响的行数为 3 行)
*/

--删除测试环境
Drop table T_table
Drop Trigger T_T_Table
lsqkeke 2006-03-10
  • 打赏
  • 举报
回复
create trigger tu_test on test
for update
as
if update(a)
begin
if exists(select 1 from deleted where a=10)
begin
rollback
raiserror ('不能修改a=10的值',16,1)
end
end

go
blueyexin 2006-03-10
  • 打赏
  • 举报
回复
二楼的兄弟理解错了,可能我说的不太清楚。我的意思是如果update的当前行列a的状态是10的话
就抱错,而不是整个表里面有a列为10的行就不行,只针对当前要update的行
lsqkeke 2006-03-10
  • 打赏
  • 举报
回复
create trigger tu_test on test
for update
as
if update(a)
if exists(select 1 from deleted where a=10)

go
lsqkeke 2006-03-10
  • 打赏
  • 举报
回复
当修改列a时,如果当前行列a的值是10
-------------------
楼上的触发器有漏洞!
如果修改了该表的其它字段,刚好那条记录的a字段的值为10
按楼主的意思,其实此时是不用报错的!
要多加个条件

wgsasd311 2006-03-10
  • 打赏
  • 举报
回复


create table test(a int)
insert into test
select 0
union select 4
union select 10

create trigger tu_test on test
for update
as
if exists(select 1 from deleted where a=10)
begin
rollback
raiserror ('不能修改a=10的值',16,1)
end
go
--test
select * from test
update test set a=1 where a=0
select * from test
update test set a=1 where a=10
select * from test
--
drop table test
wgsasd311 2006-03-10
  • 打赏
  • 举报
回复
create trigger tu_test on test
for update
as
if exists(select 1 from deleted where a=10)
rollback
go

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧