Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS SQL Server Last Inserted ID

Tags:

sql

sql-server

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)
like image 312
user2345661 Avatar asked May 08 '13 04:05

user2345661


People also ask

How do I get the last inserted record id in SQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I find the last updated id in SQL Server?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.

How can I get last inserted auto increment id in SQL Server?

Use SCOPE_IDENTITY : -- do insert SELECT SCOPE_IDENTITY(); Which will give you: The last identity value inserted into an identity column in the same scope.


1 Answers

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'
like image 177
Devart Avatar answered Sep 17 '22 10:09

Devart