MS SQL Server Last Inserted ID

后端 未结 7 974
一个人的身影
一个人的身影 2020-12-11 03:16

In my database all tables are using a common table for Sequence(ID_Table).

TABLE_ID has two fields (Common_ID, Table_Name).

If I insert any record in the tab

相关标签:
7条回答
  • 2020-12-11 04:00

    All the other answers so far declare intermediary variables for SCOPE_IDENTITY(), but it could be simpler:

    INSERT INTO dbo.TABLE_ID (Table_NAME) VALUES 'Table_Products';
    
    INSERT INTO dbo.Table_Products (ID, Product_Name) VALUES (SCOPE_IDENTITY(),'SomeProduct');
    
    0 讨论(0)
  • 2020-12-11 04:03

    Dear friend you have to select id of last record inserted and then pass it in another table so bellow code will help you very well

    Insert INTO TABLE_ID (Table_NAME), Values (Table_Products)
    DECLARE @ID int;
    set @ID = SCOPE_IDENTITY(); 
    
    Insert INTO Table_Products (ID, Product_Name) 
    Values (@ID, SomeProduct)
    

    this code will solve your problem i define @ID for your last record id and then insert it in your other table

    0 讨论(0)
  • 2020-12-11 04:09

    Try this one -

    DECLARE @ID BIGINT
    
    INSERT INTO dbo.TABLE_ID (Table_NAME) 
    SELECT 'Table_Products'
    
    SELECT @ID = SCOPE_IDENTITY()
    
    INSERT INTO dbo.Table_Products (ID, Product_Name)
    SELECT @ID, 'SomeProduct'
    
    0 讨论(0)
  • 2020-12-11 04:11

    You can use an insert statement with the output clause to generate a new Common_ID. Using insert ... select, you can specify that ID in an insert operation:

    declare @Common_ID as table(ID int)
    
    insert  Table_ID
            (Table_Name)
    output  inserted.Common_ID into @Common_ID
    values  ('Table_Products')
    
    insert  Table_Products
            (ID, Product_Name)
    select  ID
    ,       'Some Product'
    from    @Common_ID 
    
    0 讨论(0)
  • 2020-12-11 04:11

    You could be also more table-specific using IDENT_CURRENT()

    Insert INTO TABLE_ID (Table_NAME), Values (Table_Products)
    
    select @NewID=IDENT_CURRENT('TABLE_ID')
    
    Insert INTO Table_Products (ID, Product_Name, Product_ID
    Values (@NewID, SomeProduct, Increment)
    
    0 讨论(0)
  • 2020-12-11 04:18

    Use SCOPE_IDENTITY() after ur insert statementto get the last inserted id.

    DECLARE @Product_Id int
    
    INSERT INTO TABLE_ID (Table_NAME) VALUES (Table_Products);
    SELECT @Product_Id=SCOPE_IDENTITY();
    
    Insert INTO Table_Products (ID, Product_Name)
    VALUES (ID from TABLE_ID, 'SomeProduct')
    
    0 讨论(0)
提交回复
热议问题