x
login about faq Site discussion (meta-askssc)

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 '11 at 06:50 AM in Default

Murali gravatar image

Murali
896 65 105 118

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 '11 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)
select  
case
       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 '12 at 07:19 AM

sanjeev.matte gravatar image

sanjeev.matte
31 3 7 10

(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

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x916

asked: Sep 15 '11 at 06:50 AM

Seen: 398 times

Last Updated: Feb 24 '12 at 02:17 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.