【问题标题】:How to check if record exists in another table and if not then add [duplicate]如何检查另一个表中是否存在记录,如果不存在则添加[重复]
【发布时间】:2012-07-10 02:17:51
【问题描述】:

可能重复:
Insert statement that checks for duplicate before insert

我想使用外键 b_id 检查问题日志表中是否存在建筑物 ID。如果它不存在,那么我想将它添加到问题日志表中。 我有下面的代码,但这只会检查哪些建筑物不在问题日志表中......我该如何插入?非常感谢。我正在使用 SQL Server 2008。

select b.b_id from building 
where not exists(select b.b_id from issue_log as l where b._id = l.b_id)

【问题讨论】:

    标签: sql database select exists


    【解决方案1】:

    这样的?

    INSERT INTO issue_log(b_id)
    SELECT b.b_id FROM building b
    WHERE NOT EXISTS(SELECT l.b_id FROM issue_log AS l WHERE b.b_id = l.b_id)
    

    【讨论】:

      【解决方案2】:

      使用IF NOT EXISTS 或者如果您想进行更新,请使用MERGE,这将根据您在语句中设置的规则决定是否进行插入、更新或删除。一旦你掌握了语法,它就会非常有用

      MSDN:http://technet.microsoft.com/en-us/library/bb510625(v=sql.105).aspx

      【讨论】:

        猜你喜欢
        • 2021-06-19
        • 2021-03-29
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        • 2019-10-13
        • 1970-01-01
        • 2016-01-06
        • 2019-08-08
        相关资源
        最近更新 更多