Hello,

Please tell me how to create a trigger. I need to create an entry in table A to create an entry in table B with an id field equal to the id field from table A which is Auto Increment (created automatically).

MS sql 2000 sp4 version

    1 answer 1

    ALTER TRIGGER [ti_B] ON [A] FOR INSERT AS INSERT INTO [B] ([id]) SELECT [ID] FROM INSERTED RETURN 

    Regarding getting the latest ID is not as simple a question as it may seem

    Most likely, it is worthwhile to apply SELECT SCOPE_IDENTITY () after insertion into table A. This function works only inside the session and returns the ID of the last row inserted into table A.

    If it’s about getting the ID of the last inserted row regardless of the table, then you need to apply SELECT @@ IDENTITY. This feature also works inside a session. Those. if we insert a string in A, it executes a trigger for insertion. If this trigger inserts a row into some table C, in which there is some field ID with autoincrement, then SELECT @@ IDENTITY will return the ID of table C

    And the third case. If the ID is not associated with the session, use SELECT IDENT_CURRENT ('A')

    • Thank you very much! Works! Can you tell me how to get the id of the last added line in c #? - BoogVAr
    • I will add in response - renegator