Skip to content

Instantly share code, notes, and snippets.

@flying19880517
Created October 13, 2011 02:01
Show Gist options
  • Save flying19880517/1283154 to your computer and use it in GitHub Desktop.
Save flying19880517/1283154 to your computer and use it in GitHub Desktop.
使用更新锁自己处理自增主键
-- 测试表
CREATE TABLE dbo.tb(
id int PRIMARY KEY
)
INSERT dbo.tb(id)
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3
GO
BEGIN TRAN
DECLARE
@id int
SELECT @id=max(id) FROM dbo.tb WITH(UPDLOCK, HOLDLOCK)
WAITFOR DELAY '00:00:10' -- 等待 10 秒, 这里可以放你的任何处理
INSERT dbo.tb(id) values(@id+1)
COMMIT TRAN
GO
-- 更新用, 无法读取
SELECT max(id) FROM dbo.tb WITH(UPDLOCK, HOLDLOCK)
GO
-- 普通查询, 则可以读出数据
SELECT max(id) FROM dbo.tb
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment