I’m having the well known problem with a trigger and @@IDENTITY.
I created a new Auditing table and a trigger to insert auditing rows on it.
We use a software that is using @@IDENTITY and this is causing a conflict with the Id generated when the trigger insert a new row.
I have not access to the code that is using @@IDENTITY.
I need ideas on how can I generate the identity value by my self. I cannot use GUID because the order is important to me.
If I replace the Id column by a datetime column with default value GETDATE(), does it guarantee it will be unique?
Thank you
GETDATE() won’t be unique. It’s accuracy is such that multiple near concurrent events can be supplied with the same time.
If you are forced to generate your own identity values, so as not to interfere with @@IDENTITY, then you can do the following…
This is implicitly within it’s own transaction and will guarantee unique values.
EDIT
My original comment was going to be that this will NOT work when inserting multiple records, and that instead you would need to iterate through the source records individually, inserting them one at a time.
The following example, however, may be suitable to you for processing SETs of data…
This will both generate unique IDs for each row, and be safe against concurrent processes using the same code.
EDIT
I’ve added
WITH(TABLOCKX)to prevent other processes reading from the table while it’s being updated. This prevents concurrent processes from establishing the same MAX(id) and then trying to insert duplicate id’s in new records.(The single query structure already prevented records from being altered after they had been read from, but did not prevent other processes reading from the table ‘between’ the MAX(id) being read and all the new records being inserted.)