9

在我的数据库中,所有表都使用一个用于序列(ID_Table)的公用表。

TABLE_ID 有两个字段(Common_ID、Table_Name)。

如果我在表中插入任何记录,我必须首先在 Table_ID(Auto-increment, Table_name) 中插入一条记录,然后在我的其他表中使用该自动增量值。

例如,我想插入具有字段 ID(Common_ID)、Product_Name、Product_ID(Auto Increment) 的 Table_Products

我想做这样的事情:

INSERT INTO TABLE_ID (Table_NAME), Values (Table_Products)

获取插入的 ID 并在 Table_Products 中使用它:

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

7 回答 7

29

试试这个——

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'
于 2013-05-08T04:56:36.040 回答
5

您可以使用insert带有该output子句的语句来生成新的 Common_ID。使用insert ... select,您可以在插入操作中指定该 ID:

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 
于 2013-05-08T05:04:49.430 回答
4

在你的插入语句之后使用 SCOPE_IDENTITY() 来获取最后插入的 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')
于 2013-05-08T04:55:45.673 回答
2

亲爱的朋友,您必须选择插入的最后一条记录的 id,然后将其传递到另一个表中,所以下面的代码会很好地帮助您

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)

此代码将解决您的问题我为您的最后一个记录 ID 定义 @ID,然后将其插入到您的另一个表中

于 2013-05-08T05:09:38.157 回答
1

对于 MySql 使用select LAST_INSERT_ID();

于 2013-11-30T11:32:29.677 回答
0

到目前为止,所有其他答案都为 声明了中间变量SCOPE_IDENTITY(),但它可能更简单:

INSERT INTO dbo.TABLE_ID (Table_NAME) VALUES 'Table_Products';

INSERT INTO dbo.Table_Products (ID, Product_Name) VALUES (SCOPE_IDENTITY(),'SomeProduct');
于 2016-07-07T17:26:18.757 回答
-1

您还可以使用 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)
于 2013-05-08T05:07:10.710 回答