Save SQL Query Results in Variable

Solution 1:

You can use CTE to avoid looping, maybe like this:

with cte as (
      SELECT ProductName, SUM(Quantity) AS ProductQuantity FROM
      (SELECT CustomerID FROM Customers AS C
      WHERE Country = 'Germany') AS CG
      INNER JOIN Orders AS O
      ON CG.CustomerID = O.CustomerID
      INNER JOIN OrderDetails AS OD
      ON O.OrderID = OD.OrderID
      INNER JOIN Products as P
      ON OD.ProductID = P.ProductID
      GROUP BY ProductName
    )
SELECT ProductName 
FROM cte
where ProductQuantity = (SELECT MAX(ProductQuantity) FROM cte)