问题
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!
回答1:
Assuming your PK is on sessionId,variable then concurrent executions of the stored procedure with the same @sessionId,@variable could do this.
Both execute the
DELETE Variables WHERE sessionId = @sessionId AND variable = @variable
line concurrently and then both proceed to the insert.
This could only occur if there is no pre-existing record with the sessionId,variable combination as then the DELETEs would block.
来源:https://stackoverflow.com/questions/8356587/what-could-be-causing-the-primary-key-exception