MS SQL Server 最后插入的 ID [英] MS SQL Server Last Inserted ID

查看:35
本文介绍了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'

这篇关于MS SQL Server 最后插入的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆