Link to home
Start Free TrialLog in
Avatar of BobIa
BobIaFlag for United States of America

asked on

MS-SQL Stored procedure predefined for day's of the week.

I want to create a stored procedure on a MS-SQL database so that when it's called it is pre-defined to select data based on whatever day of the week it is. My issue is with when the report is run on a Monday I need to see data that may have been update during the last 3 days (Friday, Saturday and/or Sunday) all other days I only need the previous day.  I have the rest of the stored procedure worked out I'm just having trouble wrapping my head around this one exception. Here is the select code without the date parameters.  The date field I'm looking at is: "OrdDate" alias of the "dbo.OrderHeader.DateTimeLastModified" (native format DateTime)
SELECT CAST(dbo.OrderHeader.DateTimeLastModified As Date)AS OrdDate, dbo.OrderHeader.OrderNumber, dbo.OrderLine.LineNumber, dbo.AVOOption.Name AS [Installer Name], dbo.OrderLineAVO.CostPrice, dbo.OrderLineAVO.SellPrice, dbo.OrderLineAVO.TotalCostPrice, dbo.OrderLineAVO.TotalSellPrice, dbo.OrderHeader.OrderType, dbo.AVOOption.AVOID
FROM ((dbo.OrderHeader WITH(NOLOCK) INNER JOIN dbo.OrderLine WITH(NOLOCK) ON dbo.OrderHeader.OrderID = dbo.OrderLine.OrderID) INNER JOIN dbo.OrderLineAVO WITH(NOLOCK) ON dbo.OrderLine.OrderLineID = dbo.OrderLineAVO.OrderLineID) INNER JOIN dbo.AVOOption WITH(NOLOCK) ON dbo.OrderLineAVO.AVOOptionID = dbo.AVOOption.AVOOptionID
WHERE (((dbo.OrderHeader.OrderType)=5) AND ((dbo.AVOOption.AVOID)=5) AND ((dbo.OrderHeader.Deleted)=0) AND ((dbo.AVOOption.Deleted)=0)) OR (((dbo.OrderHeader.OrderType)=6) AND ((dbo.AVOOption.AVOID)=6));

Open in new window

Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Add this condition to your WHERE clause.  Technically you don't need the "<" part, but if you ever want to run for an earlier date, it could be useful to already have in there:

AND dbo.OrderHeader.DateTimeLastModified >= DATEADD(DAY, CASE WHEN DATEDIFF(DAY, 0, GETDATE()) % 7 = 0 THEN -3 ELSE -1 END, CAST(GETDATE() AS date))
AND dbo.OrderHeader.DateTimeLastModified < DATEADD(DAY, 1, CAST(GETDATE() AS date))

[Btw, note that this code works correctly under any DATEFIRST / language setting.]
Avatar of BobIa

ASKER

Scott,
This seems to return anything earlier than "today" when I run it in a select statement.  It does not seem to limit for last three days since today is Monday.

Bob
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BobIa

ASKER

This works great and also speeds the query quite a bit. Thanks Scott
You're welcome!