简体   繁体   English

Sql Server中的简单存储过程:插入桥表

[英]Simple Stored Procedure in Sql Server: Inserting into Bridge Table

I have an issue with the below stored procedure. 我的以下存储过程有问题。 It runs fine as long as I don't uncomment the last insert INSERT. 只要我不取消对最后一个插入INSERT的注释,它就可以正常运行。 If I were to uncomment the last INSERT, I get the following error: 如果要取消对最后一次INSERT的注释,则会出现以下错误:

Msg 547, Level 16, State 0, Procedure InsertRecipeWithTags, Line 42 The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Tag_TagRecipe". 消息547,级别16,状态0,过程InsertRecipeWithTags,第42行INSERT语句与FOREIGN KEY约束“ FK_Tag_TagRecipe”冲突。 The conflict occurred in database "RecipeBox", table "RecipeDetails.Tag", column 'tagID'. 数据库“ RecipeBox”的表“ RecipeDetails.Tag”的列“ tagID”中发生了冲突。 The statement has been terminated. 该语句已终止。

For clarification, I have three tables: 为了澄清起见,我有三个表:

recipe(id, title, introduction, directions)
recipeTag(id, recipeID, tagID)
tag(id, name)

So if I try to insert into the recipeTag table I get the above error. 因此,如果我尝试将其插入到recipeTag表中, recipeTag出现上述错误。 Please advise. 请指教。

Thanks. 谢谢。

CREATE PROCEDURE [RecipeDetails].[InsertRecipeWithTags]
/*
    variables that map to columns
*/
@title varchar(50),
@intro varchar(255),
@directions varchar(2200),
@ingredients varchar(2200),
@difficulty varchar(6), /*need check constraint setting difficulty to "beginner" "medium" or "expert"*/
@prepTimeHour tinyint,
@prepTimeMinute tinyint,
@inactiveTimeHour tinyint,
@inactiveTimeMinute tinyint,
@servings tinyint,
@photo varbinary(MAX),
@tagName varchar(50),
@tagdescription varchar(255)

AS

BEGIN
    SET NOCOUNT ON;

    DECLARE @RecipeID int, @TagID int

    INSERT INTO RecipeDetails.Recipe (title, intro,directions, ingredients, difficulty, 
    prepTimeHour, prepTimeMinute, inactiveTimeHour, inactiveTimeMinute, servings, photo)
    VALUES (@title, @intro,@directions, @ingredients, @difficulty, @prepTimeHour, @prepTimeMinute,
    @inactiveTimeHour, @inactiveTimeMinute, @servings, @photo)

    SELECT @RecipeID=SCOPE_IDENTITY()

    SELECT * FROM RecipeDetails.Recipe WHERE recipeID = @RecipeID;

    INSERT INTO RecipeDetails.Tag (name, description)
    VALUES (@tagName, @tagdescription)

    SELECT @TagID=SCOPE_IDENTITY()

    SELECT * FROM RecipeDetails.Tag WHERE tagID = @TagID;

    /*INSERT INTO RecipeDetails.TagRecipe (tagID, recipeID)
    VALUES (@RecipeID, @TagID)*/
END

Reverse the order? 颠倒顺序?

INSERT INTO RecipeDetails.TagRecipe (tagID, recipeID)
VALUES (@TagID, @RecipeID)

You had then the wrong way around 那你走错路了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM