SQL
CREATE FUNCTION GetTotalSalesAmount(@productId int)
RETURNS Decimal(18,2)
AS
BEGIN
DECLARE @totalSales Decimal(18,2)
select @totalSales =
sum(p.Price * ol.Quantity)
from
Products p
join OrderLines ol on p.ProductId = ol.ProductId
where p.ProductId = @productId
RETURN @totalSales
END
select dbo.GetTotalSalesAmount(2)
--manual calc to validate the function
select p.ProductId, p.Price, ol.Quantity
from
Products p
join OrderLines ol on p.ProductId = ol.ProductId
where p.ProductId = 2
SELECT
p.Name as 'Product Name',
p.Price,
c.Name as 'Category Name',
dbo.GetTotalSalesAmount(p.productId) as 'Total Sales'
FROM
Products p
join Categories c on c.CategoryId = p.CategoryId
CREATE PROCEDURE sp_GetProductInfo
@productId int
AS
BEGIN
SET NOCOUNT ON
SELECT
p.Name as 'Product Name',
p.Price,
c.Name as 'Category Name',
dbo.GetTotalSalesAmount(p.productId) as 'Total Sales'
FROM
Products p
join Categories c on c.CategoryId = p.CategoryId
WHERE p.ProductId = @productId
END
EXEC sp_GetProductInfo 1
EXEC sp_GetProductInfo @productId = 5