x

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
906 86 114 120

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 8 8 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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

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

SQL Server Central

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

Topics:

x976

asked: Sep 15 '11 at 06:50 AM

Seen: 536 times

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