select * from salgrade for update和select * from salgrade for update nowait区别

时间:2023-01-31 20:26:19

1,select * from salgrade for update

session1 session2

SQL> delete salgrade where grade=1;

1 row deleted.

 
 

SQL> select * from salgrade for update;

此时session2被阻塞

SQL> rollback;

Rollback complete.

 
 

 

     GRADE    LOSAL       HISAL
---------- ---------- ----------
     1      700        1200
     2     1201        1400
     3     1401        2000
     4     2001        3000
     5     3001        9999
被阻塞的session2立马返回了结果,但同时这句也为表加了锁

SQL> delete salgrade where grade=1;
session1被阻塞
 
 

SQL> rollback;

Rollback complete.

1 row deleted.

session1获得资源,执行完毕

 

总结来看,select * from salgrade for update有以下特征:

①如果结果集已经被另一个会话锁定,就会发生阻塞。需要等另一个会话结束之后才可继续执行。

②它会对结果集加锁

2,select * from salgrade for update nowait

session1 session2

SQL> delete salgrade where grade=1;

1 row deleted.

 
 

SQL> select * from salgrade for update nowait;
select * from salgrade for update nowait
*
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

SQL> rollback;

Rollback complete.

 
 

SQL> select * from salgrade for update nowait;

     GRADE    LOSAL       HISAL
---------- ---------- ----------
     1      700        1200
     2     1201        1400
     3     1401        2000
     4     2001        3000
     5     3001        9999

SQL> delete salgrade where grade=1;

session1此时被阻塞

 
 

SQL> rollback;

Rollback complete.

1 row deleted.

session1得到资源,执行完毕

 

总结来看,select * from salgrade for update nowait有以下特征:

①如果结果集已经被另一个会话锁定,会立即返回ORA-00054错误

②该语句本身同样也会对结果集加锁

 

综合总结,这两句语句的作用都是对结果集加排他锁,禁止其他会话做DML作业,如果希望在select期间,结果集不被修改,即可以选择这种方式。