简体   繁体   中英

SQL Server Insert if not exist

I know that SELECT + INSERT is a bad practice that can lead to race condition (learned from insert-update antipattern when some who try to implement a upsert behaviour).

But I have no idea how to avoid that when I would just insert data in a table without duplicate for a given column (or tuple of column):

IF NOT EXISTS ( SELECT TOP(1) 1 FROM [tbl_myTable] WHERE [MyNotKeyField] = 'myValue' )
BEGIN
     INSERT INTO [tbl_myTable] (...) VALUES (...)
END

Should I create an unique index and just try to insert the record anyway? I am afraid that in this case the overhead of failed insert may be more costly.

PS: I am sending that command from a client application (C# application connected with SQL Server) so I suppose temporary table and use of MERGE is out of the question.

Combine the EXISTS with INSERT

eg

INSERT INTO [tbl_myTable] (...) 
SELECT @val1, @val2 ...
WHERE NOT EXISTS
(
    SELECT 1 FROM [tbl_myTable] WITH (UPDLOCK, SERIALIZABLE)
    WHERE [MyNotKeyField] = 'myValue'
);

Aaron Bertrand has a great post on anti UPSERT patterns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM