我需要打印更新查询的回滚查询。 我的原始查询是
UPDATE EMPLOYEE SET NAME = 'SAMAN' WHERE ID=4;
上述查询的相应更新是
UPDATE EMPLOYEE SET NAME=(SELECT NAME FROM EMPLOYEE WHERE ID=4);
如果上面的原始查询出错,我需要打印一个回滚查询。我还需要它来通过查询来打印它。 我正在使用oracle 11g数据库。
答案 0 :(得分:1)
您可以通过运行如下所示的选择查询
来执行此操作SELECT 'UPDATE EMPLOYEE SET NAME = '''||name||''' WHERE id = '||id||';' FROM employee;
当然,在更新查询之前运行select查询。
答案 1 :(得分:0)
据我所知,这是你正在寻找的某种 log 表。我不知道你的意思是“打印回滚查询”;从来没有听说过这样的事情。
所以,让我展示一下我的想法。检查它,如果在您的情况下有意义,请申请。代码被评论,我希望你能理解它
准备场景:
SQL> -- Log table
SQL> create table emp_log
2 (id number constraint pk_el primary key,
3 empno number constraint fk_el_emp references emp (empno) not null,
4 datum date not null,
5 ename varchar2(20)
6 );
Table created.
SQL> -- A sequence which will be used to populate the ID column in the EMP_LOG table
SQL> create sequence seqa;
Sequence created.
SQL> -- Trigger; if new ENAME is different from the last one, log the change (i.e.
SQL> -- store the old ENAME)
SQL> create or replace trigger trg_bu_emp
2 before update on emp
3 for each row
4 begin
5 if :new.ename <> :old.ename then
6 insert into emp_log (id, empno, datum, ename)
7 values (seqa.nextval, :new.empno, sysdate, :old.ename);
8 end if;
9 end;
10 /
Trigger created.
好的,让我们看看它是如何工作的:
SQL> -- Some employees in department 10
SQL> select empno, ename from emp where deptno = 10;
EMPNO ENAME
---------- ----------
7782 CLARK
7839 KING
7934 MILLER
SQL> -- Update KING's name to a better one (just kidding)
SQL> update emp set ename = 'LITTLEFOOT' where empno = 7839;
1 row updated.
SQL> -- What's in the log?
SQL> select * From emp_log order by id desc;
ID EMPNO DATUM ENAME
---------- ---------- ------------------- --------------------
5 7839 30.03.2018 20:22:15 KING
SQL> -- I don't like the new name after all; return the previous one
SQL> update emp e set
2 e.ename = (select l.ename from emp_log l
3 where l.empno = e.empno
4 and l.id = (select max(l1.id) from emp_log l1
5 where l1.empno = l.empno
6 )
7 )
8 where e.empno = 7839;
1 row updated.
SQL> -- What we've done?
SQL> select empno, ename from emp where deptno = 10;
EMPNO ENAME
---------- ----------
7782 CLARK
7839 KING
7934 MILLER
SQL> -- What's in the log now?
SQL> select * From emp_log order by id desc;
ID EMPNO DATUM ENAME
---------- ---------- ------------------- --------------------
6 7839 30.03.2018 20:22:33 LITTLEFOOT
5 7839 30.03.2018 20:22:15 KING
SQL>