I have the following CREATE FUNCTION
:
CREATE FUNCTION ufnTotalSales (@StartDate datetime, @EndDate datetime = GETDATE(), @FoodName nvarchar(50) = '')
RETURNS TABLE
AS
RETURN
(
IF @FoodName = '';
BEGIN
SELECT f.FoodID, FoodName, (FoodPrice * Quantity) AS TotalSales FROM Food f, OrderFoodRel ofr
WHERE (Date_Time BETWEEN @StartDate AND @EndDate)
END
ELSE
BEGIN
SELECT f.FoodID, FoodName, (FoodPrice * Quantity) AS TotalSales FROM Food f, OrderFoodRel ofr
WHERE (Date_Time BETWEEN @StartDate AND @EndDate) AND @FoodName = FoodName
END
);
The first error occurs at @EndDate datetime = GETDATE()
, it says Incorrect syntax near '()'
. I'm trying to assign the @EndDate
parameter a default value of the current datetime
if the user opts to use the default value, but somehow I get an error.
The second error occurs at all the parameters that I used in IF ... ELSE
block (@FoodName
, @StartDate
and @EndDate
). It says that I Must declare the scalar variable "@..."
. It's a parameter and not a scalar variable, how do I fix this?
The idea of this function is to return the total sales of food(s) with two options: one being the total sales of a food with name X from a date to another date if you specified the food name; and two being the total sales of food(s) from a date to another date disregarding the food name.