user2345661 user2345661 - 4 months ago 6
SQL Question

MS SQL Server Last Inserted ID

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 table, I have to first insert a record in Table_ID(Auto-increment, Table_name) then use that Auto-increment value in my Other Table.

For example, I want to insert in Table_Products which has fields ID(Common_ID), Product_Name, Product_ID(Auto Increment)

I want to do something like this:

INSERT INTO TABLE_ID (Table_NAME), Values (Table_Products)


Get the Inserted ID and use it in Table_Products:

INSERT INTO Table_Products (ID, Product_Name, Product_ID(Auto Increment)
VALUES (ID from TABLE_ID, SomeProduct, Increment)

Answer

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'
Comments