违反复合主键约束

问题描述 投票:0回答:1

我正在尝试对具有复合主键的表运行更新。

相关代码:

DROP TABLE IF EXISTS a_test1

CREATE TABLE a_test1 
(
    ProjectID int NOT NULL,
    ClientID int NOT NULL,

    CONSTRAINT [PK__GC_1234] 
        PRIMARY KEY CLUSTERED (ProjectID ASC, ClientID ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                      ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

INSERT INTO a_test1 VALUES (101, 1) 
INSERT INTO a_test1 VALUES (101, 2) 
INSERT INTO a_test1 VALUES (103, 2) 
INSERT INTO a_test1 VALUES (104, 1)
INSERT INTO a_test1 VALUES (104, 2)
INSERT INTO a_test1 VALUES (104, 3)

DECLARE @newClientID int = 1


UPDATE a_test1
SET ClientID = @newClientID 
WHERE ClientID in ( 2, 3 ) 

已经有一条带有

ProjectID = 101
ClientID = 1
的记录。

违反主键约束“PK__GC_1234”。无法在对象“dbo.a_test1”中插入重复的键。重复的键值为 (101, 1)

如何添加

IF .. EXISTS
条件或联接来排除这些记录?

sql-server
1个回答
0
投票

在更新之前,您可能会先删除行,这将导致违规。

DELETE a
FROM a_test1 AS a
INNER JOIN a_test1 AS b
    ON a.ProjectID = b.ProjectID
    AND b.ClientID = @newClientID
WHERE a.ClientID IN (2, 3);
© www.soinside.com 2019 - 2024. All rights reserved.