.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> SQL Query >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

T-SQL script to find out Previous Business Day.

Posted By:Sajid P K       Posted Date: November 22, 2010    Points: 15    Category: SQL Query    URL: http://www.dotnetspark.com  

The below Code segment will return previous business day by passing parameter Date to the function. It will consider week end & Holiday.
 

To properly use this function make sure the table with field contains all annual holidays which should be manually entered into table

 

CREATE FUNCTION fn_prevbusday (@date DATETIME)
RETURNS DATETIME AS
BEGIN
DECLARE @prevbusday DATETIME, @is_not_businessday BIT

SET @prevbusday = dateadd(day, -1, @date)
SET @is_not_businessday = 1

WHILE @is_not_businessday > 0
BEGIN
 IF EXISTS (SELECT holiday_date FROM Holidays WHERE holiday_date = @prevbusday)
  SET @prevbusday = dateadd(day, -1, @prevbusday)
 ELSE
  BEGIN
   --@@DATEFIRST = 7 -> Sunday
   IF @@DATEFIRST = 7 AND DATEPART(WEEKDAY, @prevbusday) BETWEEN 2 AND 6
    SET @is_not_businessday = 0
   ELSE
    SET @prevbusday = dateadd(day, -1, @prevbusday)
   END
 END
RETURN @prevbusday
END


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend