简体   繁体   中英

Output the result of stored procedure

How can I simplify this stored procedure? It works but I think there is a better way than what I have.

SELECT TOP (1) 
    TD.FoodName, SUM(TD.Number) AS OrderCount
INTO 
    #Stemp
FROM
    tblFactor
INNER JOIN 
    tblDetail TD ON tblFactor.Factor_ID = TD.Factor_ID
WHERE 
    FactorDate = @DayDate
GROUP BY 
    TD.FoodName
ORDER BY 
    ORDERCOUNT DESC

SELECT @foodName = FoodName, @OrderCount = OrderCount  
FROM #Stemp S

Here I use #Stemp table but I think is not necessary. I also use script like this but I get an error on @OrderCount :

Msg 156, Level 15, State 1, Procedure DailyReport, Line 10 [Batch Start Line 7]
Incorrect syntax near the keyword 'AS'

Query:

SELECT TOP (1) @FoodName = TD.FoodName, @OrderCount = SUM(TD.Number) AS OrderCount
FROM tblFactor
INNER JOIN tblDetail TD ON tblFactor.Factor_ID = TD.Factor_ID   
WHERE FactorDate = @DayDate
GROUP BY TD.FoodName
ORDER BY ORDERCOUNT DESC

@FoodName and @OrderCount are output parameters

Did you try leaving off the column alias since you won't have a column -- eg

SELECT TOP (1) @FoodName=TD.FoodName, @OrderCount =SUM(TD.Number) 

and

ORDER BY SUM(TD.Number)

other than that you will need to tell us the error message in order to know what is going wrong.


or try this

SELECT TOP (1) @FoodName=Name, @OrderCount=oCount
FROM (
  SELECT TD.FoodName AS Name, SUM(TD.Number) AS oCount
  FROM tblFactor
  INNER JOIN tblDetail TD ON tblFactor.Factor_ID = TD.Factor_ID
  WHERE FactorDate = @DayDate
  GROUP BY TD.FoodName
)
ORDER BY oCount DESC

you can assign the variables directly in your select statement like so:

 SELECT TOP 1 @foodName= TD.FoodName, @OrderCount =SUM(TD.Number) 
    
    FROM tblFactor
    INNER JOIN tblDetail TD 
    ON tblFactor.Factor_ID = TD.Factor_ID
    WHERE FactorDate = @DayDate
    GROUP BY TD.FoodName
    ORDER BY SUM(TD.Number) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM