2013-07-14 77 views
0

這是我的SQL語句。它不工作。SQL Update語句,需要幫助將值傳遞給子查詢

UPDATE dbo.Smoothie 
SET TotalCalories = (SELECT 
         SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity/100 
           ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity/100 
          END) AS calories 
        FROM dbo.SmoothieIngredients AS si 
        INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id 
        WHERE si.SmoothieId = SmoothieId ---> i want to pass the SmoothieId from the main update statement to the subquery. 
        ) 

我試圖給它一個名字S2,仍然沒有工作。

UPDATE dbo.Smoothie as S2 
SET S2.TotalCalories = (SELECT 
          SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity/100 
            ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity/100 
           END) AS calories 
         FROM dbo.SmoothieIngredients AS si 
         INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id 
         WHERE si.SmoothieId = S2.SmoothieId) 

回答

2

您需要使用查詢來創建一個新表,然後將TotalCalories的值設置爲列中的值。

因此,在這種情況下:

UPDATE dbo.Smoothie 
SET  TotalCalories = s2.calories 
FROM 
    (SELECT  
     smoothieId, 
     SUM(CASE WHEN (Unit = 2) THEN f.Energ_Kcal * f.GmWt_2 * si.Quantity/100 
              ELSE f.Energ_Kcal * f.GmWt_1 * si.Quantity/100 END) AS calories 
     FROM  dbo.SmoothieIngredients AS si 
     INNER JOIN dbo.FoodAbbrev AS f ON si.FoodId = f.Id 
     GROUP BY SmoothieId 
    ) AS s2 
WHERE dbo.Smoothie.Id = s2.smoothieId 

我可以讓查詢稍有不當,但注意本集團通過在查詢S2的表,然後將行與正常Where子句鏈接。