Search code examples
sqlsql-serversql-server-2008identity-column

Reinserting rows with identity columns


I'm implementing a queue in SQL Server (2008 R2) containing jobs that are to be performed. Upon completion, the job is moved to a history table, setting a flag to success or failure. The items in the queue table has an identity column as a primary key. The history queue has a combo of this id and a time stamp as a PK.

If a job fails, I would like the option to re-run it, and they way this is thought, is to move it back from the history table and back in to the live queue. For traceability purposes, I would like to have the reinserted row have the same ID as the original entry, which causes problems as this is an identity column.

I see two possible solutions:

1) Use IDENTITY_INSERT:

SET IDENTITY_INSERT TableName ON

-- Move from history to live queue

SET IDENTITY_INSERT TableName OFF

2) Create some custom logic to generate unique IDs, like getting the max ID value from both the live and history queue and adding one.

I don't see any real problems with 2 apart from it being messy, possibly poor performance and that it makes my neurotic skin crawl...

Option 1 I like, but I don't know the implications well enough. How will this perform? And I know that doing this to two tables at the same time will make things crash and burn. What happens if two threads does this to the same table at the same time?

Is this at all a good way to do this for semi-commonly used stored procedures, or should this technique just be used for batch inserting data once in a blue moon?

Any thoughts on which is the best option, or is there a better way?


Solution

  • I'd go with Option 1 - Use IDENTITY_INSERT

    SET IDENTITY_INSERT TableName ON
    
    -- Move from history to live queue
    
    SET IDENTITY_INSERT TableName OFF
    

    IDENTITY_INSERT is a setting that applies to the current connection - so if another connection is doing similar, it will have no impact. The only place you get an error with using it is if you attempt to set it ON on another table without first turning it OFF on the first table.