【问题标题】:Updating column from one table based on changes in another table根据另一个表中的更改更新一个表中的列
【发布时间】:2013-03-01 21:27:25
【问题描述】:

请原谅我是数据库新手。我有一个食谱表格,用户可以在其中输入几种成分和食谱名称。有了这个表格,我有以下表格:Recipe{recipeID, recipeName}RecipeIngredient{recipeID,ingredientID,measurement}Ingredient{ingredientID, ingredientName}

RecipeIngredients 充当一对多关系的中间表(一个配方对许多成分)。我将 recipeID 作为该表中的外键分配给配方表中的主键 recipeID。我认为外键会根据主键更新而更新,但如果我将 RecipeIngredients 表插入到 RecipeIngredients 表中,则不会执行任何操作。

配方和配料自动分配 ID。我正在尝试将一个配方的 ID 链接到每种配料的自动分配 ID。例如,如果用户输入 8 种成分,则会为每种成分分配一个唯一 ID。我需要 RecipeIngredients 表来复制这些 ID 并将它们与自动分配的食谱 ID 相关联。

我尝试了几种解决方案来根据其他表中的更改来更新列。我已经尝试修改 this MySQL 更新语句并修改 this SQL 服务器,但我似乎无法让它们中的任何一个工作。

建议?

【问题讨论】:

    标签: c# visual-studio-2010 sql-server-ce


    【解决方案1】:

    一般来说,您需要从第一次插入中获取新的 recipeID,然后在插入成分表时使用它。

    您是否有权从插入到配方表中访问新插入的 recipeID?你是怎么做这个插入的?

    这是一个示例存储过程,它进入数据库进行插入/更新并返回 id:

    CREATE PROCEDURE [dbo].[spAlertCategoryInsUpd]
        @AlertCategoryID int,
        @AlertID int,
        @CategoryID int,
        @ScreenSortOrder int
    AS
    
    SET NOCOUNT ON
    
    IF EXISTS(SELECT [AlertCategoryID] FROM [dbo].[AlertCategories] WHERE [AlertCategoryID] = @AlertCategoryID)
    BEGIN
        UPDATE [dbo].[AlertCategories] SET
            [AlertID] = @AlertID,
            [CategoryID] = @CategoryID,
            [ScreenSortOrder] = @ScreenSortOrder
        WHERE
            [AlertCategoryID] = @AlertCategoryID
        SELECT  @AlertCategoryID as AlertCategoryID;    
    END
    ELSE
    BEGIN
        INSERT INTO [dbo].[AlertCategories] (
            [AlertID],
            [CategoryID],
            [ScreenSortOrder]
        ) 
        OUTPUT INSERTED.AlertCategoryID AS AlertCategoryID
        VALUES (
            @AlertID,
            @CategoryID,
            @ScreenSortOrder
        )
        ;
    END
    

    【讨论】:

    • 我从文本框中获取 recipeName,然后当我将配方保存到数据库时,表格会自动分配 ID。使用 string recipeQuery = "INSERT INTO Recipe (recipeName) VALUES ( '"; recipeQuery += tbRecipeName.Text + "')"; CreateCommandObject(recipeQuery, ref databaseConnection); 在分配此 ID 后,我是否必须再次插入到 RecipeIngredients 中,还是可以进行更新并将 ID 也分配给 RecipeIngredients 表?
    • 我使用存储过程来更新和插入每个字段的参数。存储过程的返回值给了我新的 id。
    • 你指的是以ID作为返回值的更新和插入函数吗?
    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2017-07-24
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多