2013-03-01 113 views
0

請原諒我,因爲我是數據庫新手。我有一個食譜形式,用戶可以輸入幾個配料和食譜名稱。通過這種形式,我有以下表格:Recipe{recipeID, recipeName}RecipeIngredient{recipeID,ingredientID,measurement}Ingredient{ingredientID, ingredientName}根據其他表中的更新更新列表

食譜成分作爲一對多關係(一個配方到許多成分)的中間表。我將recipeID作爲該表內的外鍵分配給配方表中的主鍵recipeID。我以爲外鍵會根據主鍵更新進行更新,但是如果我插入食譜表中,RecipeIngredients表將不執行任何操作。

配方和配料會自動分配ID。我試圖將一個配方的ID鏈接到每種配料的自動分配的ID。例如,如果用戶輸入8種成分,則將唯一ID分配給每種成分。我需要RecipeIngredients表來複制這些ID並將它們與自動分配的配方ID相關聯。

我已經嘗試了幾種解決方案來根據其他表中的更改更新列。我試着修改this MySQL更新聲明,並修改了this SQL服務器,但我似乎無法讓他們中的任何一個人工作。

對此提出建議?

回答

0

一般而言,您需要從第一個插入中獲取新的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 
+0

我從一個文本框獲得RecipeName中,我已表自動分配的ID時我將配方保存到數據庫。使用'string recipeQuery =「INSERT INTO Recipe(recipeName)VALUES('」; recipeQuery + = tbRecipeName.Text +'')「; CreateCommandObject(recipeQuery,ref databaseConnection);'我是否必須在分配此ID後執行另一次插入RecipeIngredients,或者是否可以執行更新並將ID分配給RecipeIngredients表? – Lohkii 2013-03-01 21:44:12

+0

我使用存儲過程來更新和插入每個字段的參數。存儲過程的返回值爲我提供了新的ID。 – Decker97 2013-03-01 21:48:22

+0

你指的是一個更新和插入ID作爲返回值的函數? – Lohkii 2013-03-04 00:01:30