我有一个存储过程,如果行键不存在,它会将一行插入到表中。它看起来是这样的:
create proc EmployeeInsertIfNotExists
(@id int, @name varchar(50))
as
begin
SET XACT_ABORT ON
begin transaction
if not exists(select * from tbl where id = @id)
insert into tbl(id, name)
values(id, name)
commit transaction
end这个存储过程实际上只有两条语句,一条select语句和一条可能的insert语句。我将两个语句都放在事务中,这样它们之间就不会发生任何导致异常的事情。id列是一个主键,所以我希望确保不会两次插入相同的id。
我的问题是:这是否足以预防问题?我需要在select语句中添加任何提示吗?如果是这样,我是否需要HOLDLOCK, TABLOCKX?这对我来说是新的素材。
编辑:建议答案
create proc EmployeeInsertIfNotExists
(@id int, @name varchar(50))
as
begin
SET XACT_ABORT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
begin transaction
if not exists(select * from tbl where id = @id)
insert into tbl(id, name)
values(id, name)
commit transaction
endhttps://stackoverflow.com/questions/38510344
复制相似问题