sql-违反唯一密钥约束

ttisahbt  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(300)

我正在尝试为以下查询找到解决方案:
存在声明的表 @Country 以及 @WHO (世界卫生组织)。
插入表中所有可能的国家/地区 @Country 进入表格 @WHO .
表的代码是:

DECLARE @Country TABLE 
(
    Id INT PRIMARY KEY IDENTITY(1,1),
    Name NVARCHAR(100),
    Capital NVARCHAR(100)
)

INSERT INTO @Country (Name, Capital) 
VALUES ('China', 'Beijing'), ('Japan', 'Tokyo'), 
       ('India', 'New Delhi'), ('South Korea', 'Seoul')

DECLARE @WHO TABLE
(
    Id INT PRIMARY KEY IDENTITY(1,1),
    Country NVARCHAR(100) UNIQUE
)

INSERT INTO @WHO (Country) 
VALUES ('Japan'), ('South Korea')

我启动的代码如下所示:

INSERT INTO @WHO (w.Country)
    SELECT DISTINCT c.Name
    FROM @Country c

SELECT w.Country 
FROM @WHO w 
ORDER BY w.Country

最终结果应为包含以下内容的表:

China
India
Japan
South Korea

我知道这可能很简单,但我似乎找不到解决办法。
我的代码遗漏了什么

tjjdgumg

tjjdgumg1#

你可以用 not exists :

INSERT INTO @WHO (w.Country)
SELECT DISTINCT c.Name
FROM @Country c
WHERE NOT EXISTS (SELECT 1 FROM @WHO w WHERE w.Country = c.Name)

另一种(可能是过度杀戮)选择是 MERGE 语法:

MERGE INTO @WHO w
USING (SELECT DISTINCT Name FROM @Country) c
ON (c.Name = w.Country)
WHEN NOT MATCHED BY TARGET
THEN INSERT (Country) VALUES(c.Country)
hk8txs48

hk8txs482#

任务的预期查询将是

INSERT INTO @WHO (Country)
SELECT
    c.Name
FROM @Country c
LEFT JOIN @WHO w ON w.Country = c.Name
WHERE w.Id IS NULL

虽然我喜欢'不存在'的版本更普遍

相关问题