SQL - 在不存在的地方插入

问题描述 投票:0回答:6

我有一个我认为完全微不足道的查询 - 如果不存在具有匹配 ID 的值,则将值插入表中:

BEGIN
   INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
   VALUES (1, 'Internal')
   WHERE NOT EXISTS( SELECT * FROM [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
END

我在 where 语句中遇到错误。为什么?我如何实现我的目标?

sql sql-server tsql sql-server-2012 sql-insert
6个回答
19
投票

您的问题来自于

WHERE
对于 UPDATE/SELECT 有效,但 INSERT 只是不明白它的含义。

但是你可以解决这个问题。将您的代码更改为:

BEGIN
   INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
   SELECT 1, 'Internal'
   WHERE NOT EXISTS( SELECT * FROM [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
END

1
投票

尝试将您的查询替换为:

BEGIN
     IF NOT EXISTS (SELECT * FROM [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
        INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID,Description) VALUES (1, 'Internal')
END

0
投票

处理此问题的正确方法是使用唯一索引/约束:

create unique index unq_Contact_Categories_Category_Id on Contact_Categories(Contact_Category_ID);

数据库将保证该列的唯一性。这可以防止竞争条件。

您可以使用

try
/
catch
来捕捉此内容:

BEGIN TRY
   INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
       SELECT 1, 'Internal';
END TRY
BEGIN CATCH
   PRINT 'Ooops';  -- you can even raise an error if you like.
END CATCH;

0
投票

为什么不使用 If 语句?

IF NOT EXISTS 
(select * from [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
  begin
    insert into [dbo].[Contact_Categories] (Contact_Category_ID, Description)
    values (1, 'Internal')
  end

这样做的优点是,如果该值存在,则不执行任何操作。类似于此处提供的答案:SQL Server IF NOT EXISTS 用法?


0
投票

我会做:

INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
   VALUES (1, 'Internal')
   WHERE 1 NOT IN ( SELECT Contact_Category_ID FROM [dbo].[Contact_Categories]) 

0
投票

我也遇到了同样的问题,这是我的解决方案。

insert into Contact_Categories (Contact_Category_ID, Description)
   select 1, 'Internal' 
where not exists 
   (select * from Contact_Categories where Contact_Category_ID = 1 and Description = 'Internal');
© www.soinside.com 2019 - 2024. All rights reserved.