i have an ssis Package which runs on business days (mon-Fri). if i receive file on tuesday , background(DB), it takes previous business day date and does some transactions. If i run the job on friday, it has to fetch mondays date and process the transactions.
i have used the below query to get previous business date
Select Convert(varchar(50), Position_ID) as Position_ID,
TransAmount_Base,
Insert_Date as InsertDate
from tblsample
Where AsOfdate = Dateadd(dd, -1, Convert(datetime, Convert(varchar(10), '03/28/2012', 101), 120))
Order By Position_ID
if i execute this query i'll get the results of yesterdays Transactios. if i ran the same query on monday, it has to fetch the Fridays transactions instead of Sundays.
9条答案
按热度按时间jrcvhitl1#
I prefer to use
DATENAME
for things like this overDATEPART
as it removes the need for SettingDATEFIRST
And ensures that variations on time/date settings on local machines do not affect the results. FinallyDATEDIFF(DAY, 0, GETDATE())
will remove the time part ofGETDATE()
removing the need to convert to varchar (much slower).EDIT (almost 2 years on)
This answer was very early in my SO career and it annoys me everytime it gets upvoted because I no longer agree with the sentiment of using DATENAME.
A much more rubust solution would be:
This will work for all language and DATEFIRST settings.
9njqaruj2#
This function returns last working day and takes into account holidays and weekends. You will need to create a simple holiday table.
ehxuflar3#
Then how about:
0md85ypi4#
The simplest solution to find the previous business day is to use a calendar table with a column called
IsBusinessDay
or something similar. The your query is something like this:The problem with using functions is that when (not if) you have to create exceptions for any reason (national holidays etc.) the code quickly becomes unmaintainable; with the table, you just
UPDATE
a single value. A table also makes it much easier to answer questions like "how many business days are there between dates X and Y", which are quite common in reporting tasks.k4ymrczo5#
You can easily make this a function call, adding a second param to replace GetDate() with whatever date you wanted. It will work for any day of the week, at any date range, if you change GetDate(). It will not change the date if the day of week is the input date (GetDate())
bfnvny8b6#
More elegant:
6tdlim6h7#
fumotvh38#
thanks for the tips above, I had a slight variant on the query in that my user needed all values for the previous business date. For example, today is a Monday so he needs everything between last Friday at midnight through to Saturday at Midnight. I did this using a combo of the above, and "between", just if anyone is interested. I'm not a massive techie.
xuo3flqw9#
Dale Kilian's code is slightly buggy, here is the corrected version, where this also considers holiday's stored in another table.
Please ignore my formatting error, I am not good at posting here.