What could be causing the primary key exception?

荒凉一梦 提交于 2019-12-10 18:36:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!