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
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');
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
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'
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
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)
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')