Reputation: 1362
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.
Upvotes: 1
Views: 5946
Reputation: 497
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
Upvotes: 6