Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert ID from IDENTITY ID of the row being inserted

I would like to know, if there is a direct way to insert ID (generated at ID column with IDENTITY(1,1)) to another columns. In another words, I am looking for SCOPE_IDENTITY() I could get at the time of inserting, not after the INSERT is commited.

I have a table, where there is a column with secondary ID (SID), which references rows from the same table and in some special cases it references itself. The only way I know to do that is to do the INSERT and consequently UPDATE SID in those cases. Simplified example:

DECLARE @ID INT
INSERT INTO Table (SID) VALUES (NULL);
SELECT @ID = SCOPE_IDENTITY();
UPDATE Table SET SID = ID WHERE ID = @ID;

There are some glitches, i.e. due to the fact that the row may or may not reference itself, etc.

like image 308
Oak_3260548 Avatar asked Dec 31 '25 10:12

Oak_3260548


1 Answers

You can do this with an AFTER INSERT trigger. In case of self-reference, leave the column NULL and have the trigger set the column equal to the IDENTITY column.

In pseudo:

  • Join the table with inserted, filter where SID is NULL
  • For those rows, update the table and set SID = ID

If it is not possible to use the NULL value, in cases where it should be possible to have no reference at all, you can use another stub value. E.g. -1 if the IDs will always be positive. In that case, apply the above way of working and substitute NULL with -1.

like image 111
TT. Avatar answered Jan 03 '26 08:01

TT.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!