如何避免在SQL Server中重复插入动态值

时间:2014-05-09 18:52:16

标签: sql sql-server select duplicate-removal notin

我想写一个查询来插入动态值,如果它们已经存在或不存在。到目前为止,我已经尝试过了。

INSERT MTB_AML..tb_aml_codes (aml_code, aml_desc)

    SELECT 'NRA', 'Non-Resident Alien'
    UNION
    SELECT 'DOM', 'Resident Alien'
    FROM MTB_AML..tb_aml_codes t1
    WHERE t1.aml_code NOT IN (SELECT t2.aml_code from MTB_AML..tb_aml_codes t2)

但是这只返回上部选择(已经存在于表中)。我做错了什么?

4 个答案:

答案 0 :(得分:1)

我认为您遇到的问题是,在您的版本中,WHERE子句仅适用于UNION子句中的最后一个选择

找出你想要的记录

 SELECT 'NRA' AS aml_code, 'Non-Resident Alien' AS aml_desc
    UNION 
 SELECT 'DOM' AS aml_code, 'Resident Alien' AS aml_desc

然后将它们包装为子查询(在示例中为[src]别名),然后您可以检查哪些目标表中没有匹配的键(别名为[dst])

INSERT MTB_AML..tb_aml_codes (aml_code, aml_desc)
SELECT src.aml_code, src.aml_desc
(
    SELECT 'NRA' AS aml_code, 'Non-Resident Alien' AS aml_desc
    UNION 
    SELECT 'DOM' AS aml_code, 'Resident Alien' AS aml_desc
) src
WHERE src.aml_code NOT IN (SELECT dst.aml_code from MTB_AML..tb_aml_codes dst)

就我个人而言,我是这样做的,但这取决于你

  INSERT MTB_AML..tb_aml_codes (aml_code, aml_desc)
SELECT src.aml_code, src.aml_desc
FROM
(
    SELECT 'NRA' AS aml_code, 'Non-Resident Alien' AS aml_desc
    UNION 
    SELECT 'DOM' AS aml_code, 'Resident Alien' AS aml_desc
) src
LEFT JOIN MTB_AML..tb_aml_codes dst
ON dst.aml_code = src.aml_code
WHERE dst.aml_code IS NULL

两者都有效,但如果必须匹配多列键,则需要使用连接方法

答案 1 :(得分:0)

您正在HARDCODING结果集的值,包装引号表示文字值,您必须要COLUMN名称。

SELECT 'DOM', 'Resident Alien'

你需要这样的SELECT:

SELECT T1.ColName, T1.AndAnotherColName
....

答案 2 :(得分:0)

您正在插入与表MTB_AML..tb_aml_codes无关的静态数据。因此,您的插入查询可以简化如下

INSERT MTB_AML..tb_aml_codes (aml_code, aml_desc)
VALUES ('NRA', 'Non-Resident Alien'),('DOM', 'Resident Alien')

修改

然后你需要检查这些值是否存在,并相应地进行插入,如下所示

IF NOT EXISTS 
(select 1 from MTB_AML..tb_aml_codes where aml_code in('NRA','DOM') 
and aml_desc in ('Non-Resident Alien','Resident Alien'))
BEGIN
INSERT INTO MTB_AML..tb_aml_codes (aml_code, aml_desc)
VALUES ('NRA', 'Non-Resident Alien'),('DOM', 'Resident Alien')
END

答案 3 :(得分:0)

我认为MERGE语句可以用于您的需求。它简洁地完成了你想要做的事情。

MERGE MTB_AML..tb_aml_codes AS dest
USING (
    -- place here whatever you want to insert if not already present
    -- I'm using something like what you have in your question since 
    -- that's your example
    SELECT 'NRA', 'Non-Resident Alien'
    UNION
    SELECT 'DOM', 'Resident Alien'
) AS src
ON dest.aml_code = src.aml_code
WHEN NOT MATCHED BY TARGET THEN
    INSERT (aml_code, aml_desc)
    VALUES (src.aml_code, src.aml_desc)
;