Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL-在不存在的地方插入_Sql_Sql Server_Sql Server 2012 - Fatal编程技术网

SQL-在不存在的地方插入

SQL-在不存在的地方插入,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我有一个我认为非常简单的查询—如果不存在具有匹配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 我在wher

我有一个我认为非常简单的查询—如果不存在具有匹配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语句周围得到一个错误。为什么?我如何实现我的目标


您的问题来自
,其中
对更新/选择有效,但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

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

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;

为什么不使用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
这样做的好处是,如果该值存在,则不执行任何操作。与此处提供的答案类似:

我会:

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

尝试将您的查询替换为:

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

可能重复的
开始插入[dbo]。[Contact\u Categories](Contact\u Categories\u ID,Description)从[dbo]。[Contact\u Categories]中选择1,“Internal”(内部),其中Contact\u Categories\u ID 1)结束
@PaulVarghese它还不存在什么?那么就没有
联系人_Category_ID=1
@VSO Check TZHX answer…这非常优雅,比IF构造更好。可选此查询必须位于事务内部,以防止争用条件,否则可能有人会在检查表和插入行之间插入一行。