在我的存储过程中,我想检查以确保表中尚不存在我尝试插入的内容。我已经尝试了下面的代码,但它似乎给了我误报(又名即使它不在表中也显示为真)。有更好的办法吗?
if not exists (select myID from tableName where myID = @myID and otherColumn = @otherColumn)
begin
insert into tableName
(
myID
, otherColumn
) values (
@myID
, @otherColumn
)
end
最佳答案
两个想法。
首先,如果涉及 NULL,您的“存在位置”逻辑可能无法按您希望的方式工作。
其次,我会尝试将其作为一个语句(因为关系数据库的 ACID 属性),而不是搞乱事务、锁以及它们的好 friend 阻塞和死锁。以下语句有效:
INSERT tableName (myId, otherColumn)
select @myId, @otherColumn
except select myId, otherColumn
from tableName
这可能不适合您,具体取决于表大小和/或索引问题;根据您的情况,其他变体也是可能的。
关于sql-server - 在插入存储过程之前检查是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266494/