This is my first shot at writing a stored procedure. I’m trying to get a list of all orders placed between two dates. I would run this proc monthly, getting the orders for the trailing 6 months. If I ran it on the 2nd or the 15th of the month, it would still take the previous 6 months from the end of the previous month.
Here’s the code:
CREATE PROCEDURE pMonthlyCustomerReport
-- Get the last day of the previous month and the first day of 6 months ago
@enddate date,
@startdate date
AS
SET @enddate = DATEADD(D,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0));
SET @startdate = DATEADD(M, DATEDIFF(MONTH, 0, GETDATE())-6, 0);
-- Get orders for the past 6 months
SELECT acct_num, date as OrderDate, type as OrderType
INTO #Orders
FROM rders
WHERE date BETWEEN @startdate AND @enddate;
When I run the proc, I get this error message:
Procedure or function ‘pMonthlyCustomerReport’ expects parameter ‘@enddate’, which was not supplied.
Any suggestions or best practices I should be using here? I may be over-thinking creating the @enddate, @startdate and should just put them in the query, but I want the variable to be declared up front.
Any thoughts?
Thanks
You can just declare the vars @startdate and @enddate instead of making them parameters to the sp, since you are setting them based on the current date anyway:
then declare it like this: