如何删除具有 2 列作为复合主键的多行

How to delete multiple rows with 2 columns as composite primary key

例如,我们有以下查询在 Oracle 中有效,但在 SQL 服务器中无效。我们如何为 SQL 服务器重写它?

delete from cpi
where (countryid, year) in (('AD', 2010), ('AF', 2009), ('AG', 1992))

相比之下,它要笨重得多,但是您可以使用 table value constructorEXISTS 子句中创建您的元组列表并以这种方式匹配它,例如

DELETE FROM cpi
WHERE EXISTS 
      ( SELECT  1
        FROM (VALUES ('AD', 2010), ('AF', 2009), ('AG', 1992)) AS v (countryid, year)
        WHERE v.countryid = cpi.countryid
        AND v.year = cpi.year
      );

如果真的只有几对,就:

 delete from cpi
 where (countryid = 'AD' and year = 2010) or (countryid = 'AF' and year = 2009) or (countryid = 'AG' and year = 1992)

或者,如果还有更多,可能是这样的:

 delete from cpi
 where countryid + '|' + convert(varchar(4),year) in ('AD|2010','AF|2009','AG|1992')

您可以使用 table-value 构造函数来表达这一点。 . .在 delete:

delete from cpi
    from (values ('AD', 2010), ('AF', 2009), ('AG', 1992) ) v(countryid, year)
    where cpi.countryid = v.countryid and cpi.year = cpi.year;

不需要子查询。