SQL Server:异常后继续插入行

时间:2018-11-17 13:22:22

标签: sql sql-server

我有一个存储过程,它会像这样插入:

    INSERT INTO [TargetTable] ([Hash], [Year], [Metadata])
        SELECT [Hash], [Year], [Metadata]
        FROM [SourceTable]

此查询将失败,因为[TargetTable]已具有数据,并且在[Hash]列上具有唯一索引。它不能插入重复项。

如何仅插入非重复项?我想我可以先选择非重复项,然后再进行插入。但是选择会更加复杂。

我尝试的另一种方法是忽略重复项。例如:

BEGIN TRY
    INSERT INTO [TargetTable] ([Hash], [Event], [Year], [Metadata])
        SELECT [Hash], [Event], [Year], [Metadata]
        FROM [SourceTable]
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
END CATCH

我期待的是类似的尝试,如果您无法插入它,请尝试插入它,然后忽略它,然后继续插入其余行。

1 个答案:

答案 0 :(得分:2)

如果没有其他插入同时发生,那么这应该起作用:

INSERT INTO [TargetTable] ([Hash], [Year], [Metadata])
   SELECT st.[Hash], st.[Year], st.[Metadata]
   FROM (SELECT st.*,
                ROW_NUMBER() OVER (PARTITION BY hash ORDER BY (SELECT NULL)) as seqnum
         FROM SourceTable st
        ) st
   WHERE seqnum = 1 AND -- ensure duplicates are not in source table
         NOT EXISTS (SELECT 1 FROM TargetTable tt WHERE tt.hash = st.hash);