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
VBdotnet2005Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun KlineLead Software EngineerCommented:
Consider reviewing Jim Horn's article on creating a Calendar table in SQL:
http://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.
PortletPaulEE Topic AdvisorCommented:
borrowing heavily from this previous comment by Scott Pletcher

DECLARE @dtDate date
SET @dtDate = GETDATE()
DECLARE @strPrevNext varchar(12)
SET @strPrevNext = 'Previous'
DECLARE @UpDown int
SET @UpDown = CASE WHEN @strPrevNext = 'Previous' then -1 ELSE 1 END

;WITH 
cteDigits
AS (
      SELECT
            0 AS digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
            SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
),
cteTally
AS ( --tally table will have 20 rows, from 0 to 19
      SELECT
            [10s].digit * 10 + [1s].digit AS tally
      FROM cteDigits [1s]
            INNER JOIN cteDigits [10s] ON [10s].digit BETWEEN 0 AND 1
)
SELECT TOP (1)
      future.[Date]
FROM (
      SELECT @dtDate AS [Date]
      ) AS nea
      CROSS JOIN cteTally t
      CROSS APPLY (
            SELECT
                  DATEADD(DAY, (t.tally+1) * @UpDown, nea.[Date]) AS [Date]
      ) AS future
WHERE DATEDIFF(DAY, 0, future.[Date]) % 7 NOT IN (5, 6)
      AND NOT EXISTS (
            SELECT
                  Holiday
            FROM tblHoliday
            WHERE Holiday = future.[Date]
      )
ORDER BY
       CASE WHEN @strPrevNext = 'Previous' THEN future.[Date] END DESC
     , CASE WHEN @strPrevNext <> 'Previous' THEN future.[Date] END ASC
;

Open in new window


CREATE TABLE tblHoliday
    ([Holiday] date)
;
    
INSERT INTO tblHoliday
    ([Holiday])
VALUES
    ('2015-11-23 00:00:00')
;

Open in new window

http://sqlfiddle.com/#!6/05518c/7

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.