MS SQL Server 最后插入的 ID
在我的数据库中,所有表都使用一个通用表作为 Sequence(ID_Table).
In my database all tables are using a common table for Sequence(ID_Table).
TABLE_ID 有两个字段(Common_ID、Table_Name).
TABLE_ID has two fields (Common_ID, Table_Name).
如果我在表中插入任何记录,我必须先在 Table_ID(Auto-increment, 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.
例如,我想在包含字段 ID(Common_ID)、Product_Name、Product_ID(Auto Increment) 的 Table_Products 中插入
For example, I want to insert in Table_Products which has fields ID(Common_ID), Product_Name, Product_ID(Auto Increment)
我想做这样的事情:
INSERT INTO TABLE_ID (Table_NAME), Values (Table_Products)
获取插入的 ID 并在 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)
试试这个 -
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'