Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL . The SP or function should calculate the next date for friday

I need to write a store procedure that will return a next friday date on a given date? for example - if the date is 05/12/2011, then it should return next friday date as 05/13/2011. If you pass, 05/16/2011, then it should return the date is 5/20/2011 (Friday). If you pass friday as the date, then it should return the same date.

like image 407
user749448 Avatar asked May 12 '11 21:05

user749448


2 Answers

I'd make this a scalar UDF as it is easier to consume the output.

CREATE FUNCTION dbo.GetNextFriday(
@D DATETIME
)
RETURNS DATETIME 
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN DATEADD(DAY,(13 - (@@DATEFIRST + DATEPART(WEEKDAY,@D)))%7,@D)
END
like image 73
Martin Smith Avatar answered Oct 16 '22 01:10

Martin Smith


This is for SQL Server 2008. To use in 2005, just change the date fields to your preference for datetime to date conversions. It also assumes you are not changing the default week begin value.

DECLARE @PassedDate date = '5/21/2011';
SELECT DATEADD(DAY,(CASE DATEPART(DW,@PassedDate) WHEN 7 THEN 6 ELSE 6 - DATEPART(DW,@PassedDate) END),@PassedDate);
like image 36
K Richard Avatar answered Oct 16 '22 00:10

K Richard