Link to home
Start Free TrialLog in
Avatar of VBdotnet2005
VBdotnet2005Flag for United States of America

asked on

Return a previous date (exclude saturday, sunday and holiday) in sql

I want to create store procedure that will return a previous date (exclude saturday, sunday and holiday)
Holiday's list in a table called 'tblHoliday'
I have below that returns only previous business day

declare @dtDate varchar(12)
set @dtDate = GETDATE()
declare @strPrevNext varchar(12)
set @strPrevNext = 'Previous'


DECLARE @intDay INT
DECLARE @rtResult DATETIME
SET @intDay = DATEPART(weekday,@dtDate)
--To find Previous working day
IF @strPrevNext = 'Previous'
IF @intDay = 1
SET @rtResult = DATEADD(d,-2,@dtDate)
ELSE
IF @intDay = 2
SET @rtResult = DATEADD(d,-3,@dtDate)
ELSE
SET @rtResult = DATEADD(d,-1,@dtDate)
--To find Next working day
ELSE
IF @strPrevNext = 'Next'
IF @intDay = 6
SET @rtResult = DATEADD(d,3,@dtDate)
ELSE
IF @intDay = 7
SET @rtResult = DATEADD(d,2,@dtDate)
ELSE
SET @rtResult = DATEADD(d,1,@dtDate)
--Default case returns date passed to function
ELSE
SET @rtResult = @dtDate
--RETURN @rtResult

print @rtResult
Avatar of Shaun Kline
Shaun Kline
Flag of United States of America image

Consider reviewing Jim Horn's article on creating a Calendar table in SQL:
https://www.experts-exchange.com/articles/20479/SQL-Server-Calendar-Table-Tips-and-Tricks.html

From there, you can use your holiday table to exclude days from the calendar table, then find the max date that exists prior to the desired date.
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia 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