有什么方法可以检查值是否在更新语句中增加了?
例如:
Table1 (id number, Value number)
Insert into Table1(id, Value) values(1, 2);
UPDATE Table1
SET value = 3
WHERE id = 1
我需要知道新值是否已递增。
谢谢
答案 0 :(得分:4)
您的问题不是很清楚,但希望以下内容可以帮助您开始。
TRIGGER table1_update BEFORE UPDATE ON table1
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
IF :NEW.value > :OLD.value then
-- value has been incremented do what you need to do
else if :NEW.value < :OLD.value then
-- value has been decremented do what you need to do
else
-- value must be the same do whatever you need to do
end if;
END;
答案 1 :(得分:2)
您可以使用returning .. into ..
结构来查看新的增量值,如下面的块所示:
SQL> create table Table1( id number, value number );
Table created
SQL> insert into Table1(id, Value) values(1, 2);
1 row inserted
SQL> set serveroutput on;
SQL>
SQL> declare
2 new_value Table1.value%type;
3 begin
4 update Table1
5 set value = 3
6 where id = 1
7 returning value into new_value;
8 dbms_output.put_line(' New Value returned is '||new_value);
9 end;
10 /
New Value returned is 3
PL/SQL procedure successfully completed
SQL> commit;
Commit complete
答案 2 :(得分:0)
触发器的问题是它不与执行代码通信。因此,如果我们需要程序根据UPDATE语句的结果选择一个或几个不同的分支,那么触发器就不好了。
我们可以使用sql%found
(或sql%notfound
)来测试我们的DML语句是否涉及任何记录。
UPDATE Table1
SET value = 3
WHERE id = 1;
if sql%found then
dbms_output.put_line('record updated');
else
dbms_output.put_line('record NOT updated');
end if;
如果我们有一条语句可能会影响多个记录,则可以使用sql%count
来获取受影响的记录数。
UPDATE Table1
SET value = 3
WHERE id > 123;
dbms_output.put_line('No of records updated = ' || sql%count);
如果要获取更新的值,请使用returning into
子句:
UPDATE Table1
SET value = value + 3
WHERE id = 1
returning value into l_value;
dbms_output.put_line('updated value = ' || l_value);