SQL Server避免使用公用表表达式的唯一约束冲突

时间:2018-06-01 18:08:59

标签: sql-server concurrency

如果我对列部门有唯一约束,并且我不希望SQL抛出唯一约束违规,而是如果该值已经存在于另一行上,我不想更新该列。如果我有两个或更多用户/连接同时执行相同的代码,这是否可以安全使用(一致性)?谢谢!

declare @piDepartment varchar(20) = 'test'
declare @piDepartmentSid int = 1105;

WITH CTE
as
(
    select top 1 1 [exists]
    from 
        dbo.tb_Department
    where
        Department = @piDepartment and
        [Department_SID] <> @piDepartmentSid
)
update D set 
    Department = @piDepartment
FROM 
    dbo.tb_Department D
    left join CTE on 1 = CTE.[exists]
where
    D.Department_SID = @piDepartmentSid and
    CTE.[exists] is null;

1 个答案:

答案 0 :(得分:0)

更安全的方法是保留唯一约束并使用TRY..CATCH块以避免在发生约束违规错误时引发错误。