Results 1 to 8 of 8

Thread: INSERT @@identity at once

  1. #1
    Join Date
    Apr 2006
    Posts
    178

    INSERT @@identity at once

    Hi

    how can I insert @@identity at once (for MS SQL 2000 / 2500)

    INSERT INTO Table1 (name) VALUES ('any')

    DECLARE @ID int SELECT @@Identity

    INSERT INTO Table2 (id_Table1) VALUES (@ID)


    does not work

    thank you

  2. #2
    Join Date
    Nov 2006
    Posts
    7
    I'm using SQL Server 7 (currently migrating to 2005), but this little change worked for me:
    Code:
    INSERT INTO Table1 (name) VALUES ('any')
    
    DECLARE @ID int 
    SET @ID = @@Identity 
    
    INSERT INTO Table2 (id_Table1) VALUES (@ID)
    You may also want to consider (if you havent done so already) putting the 2 inserts into a transaction. This will allow you to rollback the first insert if the second one fails for any reason. Depends on your needs.

    Hope this helps,

    Faris
    Last edited by Faris; 11-10-2006 at 09:16 AM.

  3. #3
    Join Date
    Nov 2002
    Location
    New Jersey, USA
    Posts
    3,932
    You have to capture @@identity immediately after insert.

    DECLARE @ID int

    INSERT INTO Table1 (name) VALUES ('any')

    SET @ID = @@Identity

    INSERT INTO Table2 (id_Table1) VALUES (@ID)

  4. #4
    Join Date
    Sep 2002
    Posts
    5,938
    Better to use SCOPE_IDENTITY( ) instead of @@Identity.

  5. #5
    Join Date
    Apr 2006
    Posts
    178
    DECLARE @ID int

    INSERT INTO Table1 (name) VALUES ('any')

    SET @ID = @@Identity

    INSERT INTO Table2 (id_Table1) VALUES (@ID)


    works perfectly

    DECLARE @ID int

    INSERT INTO Table1 (name) VALUES ('any')

    SET @ID = SCOPE_IDENTITY( )

    INSERT INTO Table2 (id_Table1) VALUES (@ID)

    i get an error on SCOPE_IDENTITY( ) invalid


    thank you

  6. #6
    Join Date
    Sep 2002
    Posts
    5,938
    Ran your code on my sql2k sp4 server without error. Keep in mind that SCOPE_IDENTITY( ) returns the last IDENTITY value inserted into an IDENTITY column in the same scope while @@Identity not limited to a specific scope.

  7. #7
    Join Date
    Apr 2006
    Posts
    178
    rmiao I dont get it

    The name "SCOPE_IDENTITY" is not permitted in this context. Valid expressions are constants, constant expressions


    INSERT INTO Table1 (name)
    VALUES ('any')

    SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]

    INSERT INTO Table2 (id_Table1)
    VALUES ([SCOPE_IDENTITY])

    does not work at all

    How can I do it ?
    thank you

  8. #8
    Join Date
    Sep 2002
    Posts
    5,938
    The code you posted before works for me, that's:

    DECLARE @ID int

    INSERT INTO Table1 (name) VALUES ('any')

    SET @ID = SCOPE_IDENTITY( )

    INSERT INTO Table2 (id_Table1) VALUES (@ID)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •