Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DATEDIFF and exclude weekends

Status
Not open for further replies.

HobbyMan

Programmer
Sep 22, 2000
25
0
0
US
I came up with this user defined function today.

Was wondering if someone would look at it and see if anything is wrong?

/*
* User Defined Function :: fn_Drop_Weekends
*
* In trying to find the datediff between two
* dates, there was a need to exclude the weekends.
* Thus this function. It will check each day between
* Begin/End. If there is a weekend day it will take
* one away from the ending date.
*
* EXAMPLE: Select AVG(Datediff(mi, Date0, dbo.Drop_Weekends(Date0,Date1)))/60.0
*
* PARAM 1 = Beginning Date
* PARAM 2 = Ending Date
*
* OUTPUT datetime
*/
CREATE FUNCTION fn_Drop_Weekends ( @DATE_BEGIN datetime, @DATE_END datetime )
RETURNS datetime
AS
BEGIN

DECLARE @dateB datetime
SET @dateB=@DATE_BEGIN

DECLARE @dateE datetime
SET @dateE=@DATE_END

DECLARE @returnDate datetime
SET @returnDate=@DATE_END

WHILE @dateB < @dateE
BEGIN
IF DATEPART (dw, @dateB) IN (1,7)
BEGIN
SET @returnDate = @returnDate - 1
END

SET @dateB = @dateB + 1
END
RETURN (@returnDate);
END
 
It seems to me that the DATEPART for the day of the week is non-deterministic because of firstday and shouldn't work in a user defined function. I tried and seems to work. (Head scratching). JHall
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top