I need to validate if a record already exists. The portion, in the stored procedure, that does that is:
SELECT EXISTS (SELECT 1 FROM MyTable
WHERE FirstName = @FirstName
AND LastName = @LastName
AND Address = @Address)
BEGIN
SET @IsNewRecord = 1
END
IF @IsNewRecord = 1
BEGIN
INSERT INTO MyTable
VALUES (@FirtName, @LastName, @Addres, @City, @Phone)
END
That works fine, the issue is when the stored procedure is called by several clients at the same time, it will return the @IsNewRecord = 1
.
I already tried surrounding the validation among a TRANSACTION BLOCK
, but it still creates a new record.
How can I handle concurrency when using SELECT
?