请教一个简单的触发器

chenyao023 2009-11-28 12:23:51
table1 有3个字段(序号,字母 varchar2,数字 varchar2)

序号 字母 数字
001 A 2
002 E 5

如果更新的值是 '不变',那么值不变

例 update table1 set 字母='不变',数字='100' where 序号=001
update table1 set 字母='不变',数字='不变' where 序号=002

更新后:序号 字母 数字
001 A 100
002 E 5

请问这个触发器该怎么写
...全文
60 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
huangyunzeng2008 2009-11-28
  • 打赏
  • 举报
回复
为什么要这样做呢?感觉需求真的很怪异!
BenChiM888 2009-11-28
  • 打赏
  • 举报
回复

--更新后抛异常信息的写法。
create or replace trigger trigger_table1
before update on table1
for each row
when(new.字母='不变' or new.数字='不变')
begin
raise_application_error('-20001','字段[字母]或者[数字]不允许更新成[不变]');
end;
/

--更新后把原值更新回去的写法。
create or replace trigger trigger_table1
before update on table1
for each row
when(new.字母='不变' or new.数字='不变')
begin
:new.字母=:old.字母;
:new.数字=:old.数字;
end;
/


crazylaa 2009-11-28
  • 打赏
  • 举报
回复

SQL> drop table table1;

表已丢弃。

SQL> create table table1(序号 varchar2(100),字母 varchar2(100),数字 varchar2(100));

表已创建。

SQL> insert into table1 values('001','A','2');

已创建 1 行。

SQL> insert into table1 values('002','E','5');

已创建 1 行。

SQL> select * from table1;

序号 字母 数字
---------- ---------- ----------
001 A 2
002 E 5

SQL> create or replace trigger t_update_test
2 before update on table1
3 for each row
4 when(new.字母='不变' or new.数字='不变')
5 begin
6 if :new.字母 = '不变' then
7 :new.字母 := :old.字母;
8 end if;
9 if :new.数字 = '不变' then
10 :new.数字 := :old.数字;
11 end if;
12 end;
13 /

触发器已创建

SQL>
SQL> update table1 set 字母='不变',数字='100' where 序号='001';

已更新 1 行。

SQL> update table1 set 字母='不变',数字='不变' where 序号='002';

已更新 1 行。

SQL> select * from table1;

序号 字母 数字
---------- ---------- ----------
001 A 100
002 E 5

SQL>
小灰狼W 2009-11-28
  • 打赏
  • 举报
回复
create or replace trigger tgname
before update on table1
for each row
when(new.字母='不变' or new.数字='不变')
begin
if :new.字母='不变' then
:new.字母:=:old.字母;
end if;
if :new.数字='不变' then
:new.数字:=:old.数字;
end if;
end;

不过一般不要这样用,既然不需要更新为什么要更新成'不变'...
update table1 set 数字='100' where 序号=001 不就好了

17,137

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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