小编典典

插入多行,但每行检查它是否不存在

sql

EXIST如果它们不在目标表中,我希望插入多行。但我不确定如何使用以下代码执行此操作:

INSERT INTO sales.promotions(
    promotion_name,
    discount,
    start_date,
    expired_date
)
VALUES
('2019 Summer Promotion', 0.15, '20190601', '20190901'),
('2019 Fall Promotion',   0.20, '20191001', '20191101'),
('2019 Winter Promotion', 0.25, '20191201', '20200101');

因为该WHERE NOT EXIST子句将适用于所有行,而我需要逐行执行:

WHERE NOT EXISTS (SELECT * FROM sales.promotions
    WHERE promotion_name = 'Winter Promotion');

对不起,如果这很明显,不太擅长 SQL,我不确定如何用适当的研究来表达这个问题。


阅读 211

收藏
2022-07-22

共1个答案

小编典典

可以使用表值构造函数exists

INSERT INTO sales.promotions(promotion_name, discount, start_date, expired_date)
SELECT *
FROM (VALUES
    ('2019 Summer Promotion', 0.15, '20190601', '20190901'),
    ('2019 Fall Promotion',   0.20, '20191001', '20191101'),
    ('2019 Winter Promotion', 0.25, '20191201', '20200101')
) AS values_tobe_inserted(promotion_name, discount, start_date, expired_date)
WHERE NOT EXISTS (
    SELECT *
    FROM sales.promotions
    WHERE sales.promotions.promotion_name = values_tobe_inserted.promotion_name
)
2022-07-22