如何使用输出语句并使用该id插入多个值

时间:2013-05-21 09:22:25

标签: sql sql-server

我想将值插入两个表中。

第一个看起来像这样

食谱

RecipeId (unique and AI)
RecipeName
Method
Discontinued

第二个看起来像这样

IngredientRecipe

RecipeUniqId (unique and AI)
RecipeId (same as the RecipeId in the Recipes table)
IngredientId 

我想插入RecipeName和Method。如果我这样做,RecipeId会自动递增。比我想用RecipeId插入三倍的成分。它为一种成分工作。

INSERT INTO Recipes (RecipeName, Method, Discontinued)
OUTPUT INSERTED.RecipeId, '5'
INTO IngredientRecipe(
    RecipeId,
    IngredientId
)

VALUES ('Potato and Chips', 'Potato and Chips bake everything', 'false');

所以我想要的是,我可以为IngredientId添加相同RecipeId三倍的不同数字。

怎么做?我使用sql server

编辑:

我使用带有c#的asp.net和一个N层结构。我使用的是sql server数据库

1 个答案:

答案 0 :(得分:1)

声明一个变量并存储使用的主键的值

declare @id int

将数据插入Receipes表并使用SCOPE_IDENTITY功能(有关详情,请参阅this

 INSERT INTO Recipes (RecipeName, Method, Discontinued) VALUES (....)
 SELECT @id = SCOPE_IDENTITY

使用值

重复插入成分
INSERT INTO IngredientRecipe(RecipeId,  IngredientId) VALUES (@id, ...)
INSERT INTO IngredientRecipe(RecipeId,  IngredientId) VALUES (@id, ...)
...
相关问题