dates issue

declare @date datetime = '2011/09/25',@days = 2
requirement is for the given days previous 2 days has to calculate like

 set @date = dateadd(dd,-@days,@date)

suppose in between those todays if any saturday and sunday comes in then it should return the previous dates.

suppose if we pass @days as 1, then it should check if the previous day is a saturday or sunday, if it is saturday or sunday then previous day should return

more ▼

asked Sep 15, 2011 at 06:50 AM in Default

avatar image

906 109 119 123

What if @days = 10? Should it remove only workdays or should it remove 10 days and then another 1 or 2 if the result is saturday or sunday? If original day is Wednesday September 14th, what should be the result if @days=10? Wednesday September 1st or Friday September 3rd?

Sep 15, 2011 at 10:23 AM Magnus Ahlkvist
(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

Hi, Please try this code and let me know if you have any concerns regarding the code.

 declare @date datetime = '2011/09/25',@days int= 13,@date1 datetime
 set @date1 = dateadd(dd,-@days,@date)
         when datename(DW,@date1)='saturday'   
             then dateadd(dd,-1,@date1)
         when datename(DW,@date1)='sunday' OR datename(DW,@date)='sunday'
             then dateadd(dd,-2,@date1)
 else dateadd(dd,-@days,@date)
 end as result
more ▼

answered Feb 24, 2012 at 07:19 AM

avatar image

31 8 8 13

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.



asked: Sep 15, 2011 at 06:50 AM

Seen: 701 times

Last Updated: Feb 24, 2012 at 02:17 PM

Copyright 2018 Redgate Software. Privacy Policy