我想向表中插入数据,但只插入数据库中不存在的数据。

这是我的代码:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   INSERT INTO EmailsRecebidos (De, Assunto, Data)
   VALUES (@_DE, @_ASSUNTO, @_DATA)
   WHERE NOT EXISTS ( SELECT * FROM EmailsRecebidos 
                   WHERE De = @_DE
                   AND Assunto = @_ASSUNTO
                   AND Data = @_DATA);
END

错误是:

Msg 156,级别15,状态1,程序EmailsRecebidosInsert,第11行 关键字WHERE附近的语法不正确。


当前回答

如果你的聚集索引只包含这些字段,那么简单、快速和可靠的选择是使用IGNORE_DUP_KEY

如果您使用IGNORE_DUP_KEY ON创建群集索引

然后你可以使用:

INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE, @_ASSUNTO, @_DATA)

这在任何情况下都是安全的!

其他回答

我会使用合并:

create PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   with data as (select @_DE as de, @_ASSUNTO as assunto, @_DATA as data)
   merge EmailsRecebidos t
   using data s
      on s.de = t.de
     and s.assunte = t.assunto
     and s.data = t.data
    when not matched by target
    then insert (de, assunto, data) values (s.de, s.assunto, s.data);
END

您可以使用GO命令。这将在错误发生后重新启动SQL语句的执行。在我的情况下,我有一些1000 INSERT语句,其中一些记录已经存在于数据库中,我只是不知道是哪一个。 我发现在处理了几个100之后,执行就会停止,并出现一个错误消息,它不能插入,因为记录已经存在。很烦人,但按GO键解决了这个问题。这可能不是最快的解决方案,但速度不是我的问题。

GO
INSERT INTO mytable (C1,C2,C3) VALUES(1,2,3)
GO
INSERT INTO mytable (C1,C2,C3) VALUES(4,5,6)
 etc ...

如果你的聚集索引只包含这些字段,那么简单、快速和可靠的选择是使用IGNORE_DUP_KEY

如果您使用IGNORE_DUP_KEY ON创建群集索引

然后你可以使用:

INSERT INTO EmailsRecebidos (De, Assunto, Data) VALUES (@_DE, @_ASSUNTO, @_DATA)

这在任何情况下都是安全的!

INSERT命令没有WHERE子句——你必须这样写:

ALTER PROCEDURE [dbo].[EmailsRecebidosInsert]
  (@_DE nvarchar(50),
   @_ASSUNTO nvarchar(50),
   @_DATA nvarchar(30) )
AS
BEGIN
   IF NOT EXISTS (SELECT * FROM EmailsRecebidos 
                   WHERE De = @_DE
                   AND Assunto = @_ASSUNTO
                   AND Data = @_DATA)
   BEGIN
       INSERT INTO EmailsRecebidos (De, Assunto, Data)
       VALUES (@_DE, @_ASSUNTO, @_DATA)
   END
END

我用SQL Server 2012做了同样的事情,它工作

Insert into #table1 With (ROWLOCK) (Id, studentId, name)
SELECT '18769', '2', 'Alex'
WHERE not exists (select * from #table1 where Id = '18769' and studentId = '2')