尝试使用3个主键更新行不起作用

时间:2019-04-16 07:17:30

标签: sql sql-server tsql

我有一个表,该表具有一行的3个主键,每当我尝试更新该行时,都会显示“无法插入重复值”,但是我试图使用UPDATE命令而不是INSERT来更新该行?

CREATE TABLE dbo.TestData
(
    OgrId int NOT NULL,
    StrId int NOT NULL,
    UserId int NOT NULL,
    ProductId int NOT NULL,
    CONSTRAINT PK_OgrId_StrId_UserId
        PRIMARY KEY(OgrId, StrId, UserId)
)

DECLARE @ogrId int = 99;
DECLARE @strId int = 44;
DECLARE @userId int = 1223;
DECLARE @id int = 14;

DECLARE @querySelect int = 
    (SELECT ProductId FROM dbo.TestData
        WHERE
            OgrId = @ogrId AND 
            StrId = @strId AND 
            UserId = @userId AND
            ProductId= @id);
IF @querySelect IS NULL
    BEGIN
        INSERT INTO dbo.TestData(OgrId, StrId, UserId, ProductId)
        VALUES (@ogrId , @strId , @userId, @id);
    END
ELSE
    BEGIN
        UPDATE dbo.TestData
        SET ProductId= @id
        WHERE 
            OgrId = @ogrId AND 
            StrId = @strId AND 
            UserId = @userId;
    END

1 个答案:

答案 0 :(得分:0)

您的问题是您不是在真正调用UPDATE,而是在调用INSERT(试图创建重复的密钥)。

这是因为您要检查主键值和产品ID是否存在一行。当您尝试将同一行更改为其他产品ID时,您的支票将返回false。

我对您的代码进行了少许更改,因此您只检查主键值的当前产品ID,仅在不存在主键值时插入它,而在不相同时才更新它。

CREATE TABLE dbo.TestData
(
    OgrId int NOT NULL,
    StrId int NOT NULL,
    UserId int NOT NULL,
    ProductId int NOT NULL,
    CONSTRAINT PK_OgrId_StrId_UserId
        PRIMARY KEY(OgrId, StrId, UserId)
)

DECLARE @ogrId int = 99;
DECLARE @strId int = 44;
DECLARE @userId int = 1223;
DECLARE @id int = 14;

DECLARE @querySelect int = 
    (SELECT ProductId FROM dbo.TestData
        WHERE
            OgrId = @ogrId AND 
            StrId = @strId AND 
            UserId = @userId);

IF @querySelect IS NULL
    BEGIN
        INSERT INTO dbo.TestData(OgrId, StrId, UserId, ProductId)
        VALUES (@ogrId , @strId , @userId, @id);
    END
ELSE IF @querySelect <> @id
    BEGIN
        UPDATE dbo.TestData
        SET ProductId= @id
        WHERE 
            OgrId = @ogrId AND 
            StrId = @strId AND 
            UserId = @userId;
    END