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

时间:2011-01-13 23:59:58

标签: sql sql-server

我遇到以下存储过程的问题。只要我不取消注释最后一次插入INSERT,它就可以正常运行。如果我要取消注释最后一次INSERT,我会收到以下错误:

  

Msg 547,Level 16,State 0,Procedure   InsertRecipeWithTags,第42行   INSERT语句与   FOREIGN KEY约束   “FK_Tag_TagRecipe”。冲突   发生在数据库“RecipeBox”中,   表“RecipeDetails.Tag”,列   “标签识别”。声明一直如此   终止。

为了澄清,我有三个表:

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

因此,如果我尝试插入recipeTag表,我会收到上述错误。请指教。

感谢。

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

1 个答案:

答案 0 :(得分:3)

撤销订单?

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

你有错误的方法