假设我有两列 CategoryId 和 SubcategoryId。对于每个 CategoryId,SubcategoryId 从 1 开始。插入新的子类别时,我需要为给定的 CategoryId 计算 MAX(SubcategoryId)+1。
以下是正确的吗?
BEGIN TRANSACTION
DECLARE @NextId bigint;
SELECT @NextId = ISNULL(MAX(SubcategoryId),0) + 1
FROM Subcategory WITH (UPDLOCK, HOLDLOCK)
WHERE CategoryId = @CategoryId;
INSERT INTO Subcategory
(
CategoryId,
SubcategoryId
)
VALUES
(
@CategoryId,
@NextId
);
COMMIT
WITH(UPDLOCK, HOLDLOCK) 是否也防止同时插入具有相同 CategoryId 的新行,还是仅锁定在 SELECT 时匹配的现有行?如果是后者,我应该将其更改为 TABLOCK 吗?是否也需要某种排他锁?