Key violation PRIMARY (duplicate key) on the table, where PK is the identifier?

So I have this table:

CREATE TABLE [Snapshots].[Crashproof](
    [EmoteCountId] [int] IDENTITY(1,1) NOT NULL,
    [SnapshotId] [int] NOT NULL,
    [Emote] [nvarchar](42) NOT NULL,
    [EmoteCountTypeId] [int] NOT NULL,
    [Count] [decimal](19, 6) NOT NULL,
    CONSTRAINT [PK_SnapshotsCrashproof] PRIMARY KEY CLUSTERED ([EmoteCountId] ASC) ON [PRIMARY],
    CONSTRAINT [FK_SnapshotsCrashproof_Snapshots] FOREIGN KEY ([SnapshotId]) REFERENCES [Snapshots].[Snapshots] ([SnapshotId]) ON DELETE CASCADE,
    CONSTRAINT [FK_SnapshotsCrashproof_EmoteCountTypes] FOREIGN KEY ([EmoteCountTypeId]) REFERENCES [dbo].[EmoteCountTypes] ([EmoteCountTypeId])
) ON [PRIMARY]
GO

and this code that inserts into it:

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, trans))
{
    bulkCopy.DestinationTableName = "Snapshots.Crashproof";
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("SnapshotId", "SnapshotId"));
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("EmoteCountTypeId", "EmoteCountTypeId"));
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Emote", "Emote"));
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping("Count", "Count"));

    using (IDataReader reader = ObjectReader.Create(emoteCountTypesToSnapshot))
    {
        bulkCopy.WriteToServer(reader);
    }
}

it works fine 99.99% of the time (and a bulk copy runs every minute), however, I had an exception once, it was on the last line ( bulkCopy.WriteToServer(reader);):

Violation of PRIMARY KEY restriction ... It is not possible to insert a duplicate key into the Snapshot .Crashproof object. The duplicate key value is (247125).

I get that bulk paste directly to the final table is not recommended, I will modify my code to bulk paste into the staging table, and then paste from there. But did this cause this exception?

I really do not understand how a duplicate key can occur in the "Identification" field: |

+4
1

- ETL . ​​ . ( ) .

Pentaho Kettle . , , , , / .

, , , - .

0

Source: https://habr.com/ru/post/1650804/


All Articles