I have a table similar to this one...
CREATE TABLE [Customer]
(
[Id] BIGINT IDENTITY NOT NULL,
[AccountName] CHARACTER VARYING(255),
CONSTRAINT [PK_Customer_Id] PRIMARY KEY ([Id]),
CONSTRAINT [UQ_Customer_AccountName] UNIQUE ([AccountName])
)
I want to execute this query concurrently from many applications...
IF NOT EXISTS(SELECT [AccountName] FROM [Customers] WITH (UPDLOCK, HOLDLOCK) WHERE [AccountName] = 'SuperCustomer') THEN
BEGIN
INSERT INTO [Customers] ([AccountName]) VALUES ('SuperCustomer');
END
Would the WITH (UPDLOCK, HOLDLOCK)
prevent concurrent execution of this query from attempting the insert with the same AccountName
value even if the row does not exist yet by holding the update lock on the index of the non existent data? I want to avoid termination due to a unique constraint violation on AccountName
in the Customer
table in all cases if a user tries to submit the same customer for creation twice at the same time or in high volume maliciously for whatever reason. We're operating with SET XACT_ABORT ON
and this will be inside a transaction that is at the READ COMMITTED
isolation level.