我该如何在不存在的地方插入? [英] How can I do an insert where not exists?

查看:86
本文介绍了我该如何在不存在的地方插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将插入查询与不存在的地方"组合在一起,以免违反PK约束.但是,如下所示的语法给了我Incorrect syntax near the keyword 'WHERE'错误-

I'd like to combine an insert query with a "where not exists" so as not to violate PK constraints. However, syntax such as the following gives me an Incorrect syntax near the keyword 'WHERE' error -

INSERT INTO myTable(columns...)
VALUES(values...)
WHERE NOT EXISTS
   (SELECT *
    FROM myTable
    WHERE pk_part1 = value1,
        AND pk_part2 = value2)

我该怎么做?

(通常,您可以将插入内容与where子句结合使用吗?)

(In general, can you combine an insert with a where clause?)

推荐答案

INSERT INTO myTable(columns...)
Select values...
WHERE NOT EXISTS
   (SELECT *
    FROM myTable
    WHERE pk_part1 = value1,
        AND pk_part2 = value2)

修改: 阅读马丁斯链接后,如果可以接受,最好的解决方案是:

After reading martins link, If admit, that the best solution is:

BEGIN TRY
    INSERT INTO myTable(columns...)
    values( values...)
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() <> 2627
      RAISERROR etc
END CATCH;

这篇关于我该如何在不存在的地方插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆