gpt4 book ai didi

oracle - FOR UPDATE OF和FOR UPDATE之间的区别

转载 作者:行者123 更新时间:2023-12-04 05:24:54 26 4
gpt4 key购买 nike

当我使用FOR UPDATE OF SAL或简单地编写FOR UPDATE时,有什么不同?

根据O'Reilly

The OF list of the FOR UPDATE clause does not restrict you to changing only those columns listed. Locks are still placed on all rows; the OF list just gives you a way to document more clearly what you intend to change. If you simply state FOR UPDATE in the query and do not include one or more columns after the OF keyword, then the database will then lock all identified rows across all tables listed in the FROM clause.



这意味着,当我使用 FOR UPDATE OF SAL指定列名时,其他用户只能使用 SAL列进行更改。但是,实际上并非如此。我仍然在其他 session 中处于锁定状态。谁能解释其中的区别。

更新
 ----- SESSION 1

declare
emp_info emp.ename%type;
cursor emp_cur is select ename from emp join dept using(deptno) where deptno=&no for update of sal;
begin
open emp_cur;
loop
fetch emp_cur into emp_info;
exit when emp_cur%notfound;
dbms_output.put_line(emp_info);
end loop;
close emp_cur;
end;

----- SESSION 2

update emp set comm=5 where deptno=10;
---- hanged/waiting in session 2

最佳答案

Oracle documentation:

Use the OF ... column clause to lock the select rows only for a particular table or view in a join. The columns in the OF clause only indicate which table or view rows are locked. The specific columns that you specify are not significant. However, you must specify an actual column name, not a column alias. If you omit this clause, then the database locks the selected rows from all the tables in the query.



如果查询引用单个表,则 FOR UPDATEFOR UPDATE OF ...之间没有区别,但是后者可能仍然可以用作自我文档,以指示要更新的列。它并没有限制您可以更新的内容。如果你有:
CURSOR cur IS SELECT * FROM emp FOR UPDATE OF sal;

那么您仍然可以执行以下操作:
UPDATE emp SET comm = comm * 1.1 WHERE CURRENT OF cur;

但是,如果有多个表,那么 FOR UPDATE OF ...将仅锁定表中包含您在 OF子句中指定的列的行。

与我认为您在问题中所说的相反。指定 FOR UPDATE OF sal不仅会锁定 sal列;您永远不能锁定单列,最小锁定是在行级别。 ( Read more about locks)。它锁定表中包含 SAL列的所有行,这些行由查询选择。

在对问题的更新中,您的游标查询将 empdept结合在一起,但是 OF子句仅包含 sal,即 emp表中的一列。打开游标时, emp表中的行将被锁定,并且只有在您对该 session 进行 commitrollback时,这些锁才会被释放。在游标循环中,您可以执行以下操作:
UPDATE emp SET ... WHERE CURRENT OF emp_cur;

...以更新 emp表中与该循环迭代有关的行。您不能执行以下操作:
UPDATE dept SET ... WHERE CURRENT OF emp_cur;

...因为 dept表中的行未锁定,因为 OF中没有列。这也意味着在您的第二个 session 中, dept行可以自由更新,因为它们没有被第一个 session 锁定。

关于oracle - FOR UPDATE OF和FOR UPDATE之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16081582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com