Based on my previous question, I'm trying to print various columns from different tables and only print the top 10 most profitable products and it is calculated by sellingprice - costprice. How can I print out the top 10 output line by line like its on a table?
CREATE PROCEDURE usp_top10ProfitableProducts
@productID int Output,
@productdes VARCHAR(100) Output,
@quantityorder int Output,
@totalProfit DECIMAL(5,2) Output
AS
BEGIN
SELECT Top 10 *
FROM
(SELECT
@productID = productID,
@productdes = Product.description,
@quantityorder = CustomerInventory.quantityOrdered, @totalProfit = (Inventory.sellingPrice-Inventory.costPrice) AS difference
FROM
Product p, Supplier s, SupplierOrder so, Inventory in, CustomerInventory cin
WHERE
p.ProductID = s.productID, s.supplierID = so.supplierID, so.supOrderID = in.supOrderID, in.barcodeNo = cin.barcodeNo) difference_data
ORDER BY
difference DESC
DECLARE @productID INT
DECLARE @productdes VARCHAR(100)
DECLARE @quantityorder INT
DECLARE @totalProfit DECIMAL(5,2)
EXECUTE usp_top10ProfitableProducts
@productID OUT
@productdes OUT
@quantityORDER OUT
@totalProfit OUT
PRINT
Instead of a procedure, use a view. However, there are other things to fix:
FROM
clause. Always use explicit JOIN
syntax. The view looks like:
CREATE VIEW vw_top10ProfitableProducts as
SELECT Top 10 p.productID, p.description, ci.quantityOrdered,
(i.sellingPrice - i.costPrice) as Difference
FROM Product p JOIN
Supplier s
ON p.ProductID = s.productID JOIN
SupplierOrder so
ON s.supplierID = so.supplierID JOIN
Inventory in
ON so.supOrderID = in.supOrderID JOIN
CustomerInventory cin
ON in.barcodeNo = cin.barcodeNo
ORDER BY difference Desc;
You can then access it just like a regular table:
select *
from vw_top10ProfitableProducts;
This is much easier than using stored procedures. In any case, your stored procedure could never work, because you want to return ten rows, but you have only four output parameters.
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.