My ASP pages store session variables in SQL Server with the following stored procedure:
CREATE PROCEDURE [dbo].[MyProcedure]
@sessionId varchar(512),
@variable varchar(350),
@value image
AS
BEGIN
BEGIN TRAN
DECLARE @result int = 0;
DECLARE @locked bit;
IF (SELECT COUNT(*) FROM Sessions WHERE id = @sessionId) = 0
BEGIN
SET @result = -1;
END
ELSE BEGIN
DELETE Variables WHERE sessionId = @sessionId AND variable = @variable
IF @value IS NOT NULL
BEGIN
INSERT Variables VALUES(@sessionId, @variable, @value, 0)
END
END
COMMIT TRAN
RETURN @result
END
But once in a while, I get a primary key exception (Msg 2627): “Violation of PRIMARY KEY constraint ‘PK_Variables’. Cannot insert duplicate key in object ‘dbo.Variables'”.
Note: There are no triggers involved.
Thanks!
Assuming your PK is on
sessionId,variablethen concurrent executions of the stored procedure with the same@sessionId,@variablecould do this.Both execute the
line concurrently and then both proceed to the
insert.This could only occur if there is no pre-existing record with the
sessionId,variablecombination as then theDELETEs would block.