0

这是我的 SQL 语句。它不工作。

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)
4

1 回答 1

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 表中的 Group By,然后将行与 Where 子句正常链接。

于 2013-07-14T14:00:07.560 回答