1. SQLserver锁表的六种语法
SELECT * FROM table WITH (TABLOCKX)
SELECT * FROM table WITH (XLOCK)
--查询过程中,其他会话无法查询、更新此表,直到查询过程结束
SELECT * FROM table WITH (UPDLOCK)
SELECT * FROM table WITH (TABLOCK)
SELECT * FROM table WITH (HOLDLOCK)
--查询过程中,其他会话可以查询,但是无法更新此表,直到查询过程结束
SELECT * FROM table WITH (NOLOCK)
--查询过程中,其他会话可以查询、更新此表
2. 举例
-- 表test的数据如下
Select id,salary FROM test;
-- id salary
-- 1 9999.00
-- 2 8888.88
-- 会话1:(UPDATE没有提交,加锁)
BEGIN TRAN;
Update test Set salary=5000.00 Where id=2;
--ROLLBACK;
-- 会话2:堵塞了
Select id,salary FROM test;
-- 会话3:正常,但是查询到的数据是脏数据,salary=5000.00是没有提交也没有回滚的数据
Select id,salary FROM test WITH(NOLOCK);
-- id salary
-- 1 9999.00
-- 2 5000.00
-- 会话一:锁表 test WITH (TABLOCKX) 直到COMMIT/ROLLBACK解锁
BEGIN TRAN;
Select count(*) From test WITH (TABLOCKX);
-- 会话二:堵塞了,test被锁不能查询更新
Select * From test;
GO
Update test Set salary=8888.88 Where id=2;
GO
3. PB锁表语句
Execute Immediate "SELECT top 1 txm FROM WT_xz45 WITH(TABLOCKX)" Using SQLCA;
--//直到事务COMMIT/ROLLBACK解锁