Tuesday, December 1, 2009

Function returning second Tuesday of the month

Function below returns second Tuesday of the month. The month is taken from the datetime variable passed as an argument. One can pass today's date to the function to get second Tuesday of the current month. At my job there is patching done every Tuesday, so a lot of things I deal with depend on that date - second Tuesday


CREATE FUNCTION dbo.getSecondTuesday
(@dt DATETIME)
RETURNS DATETIME
AS

BEGIN

DECLARE @firstDayOfMonth DATETIME

SET @firstDayOfMonth=DATEADD(mm, DATEDIFF(m, 0, @dt), 0)

DECLARE @dayWeek int
SET @dayWeek = DATEPART(DW,@firstDayOfMonth)
DECLARE @count int
SET @count = ((10 - @dayWeek) % 7) + 7

DECLARE @outputDate datetime

SET @outputdate = CONVERT(VARCHAR(10),DATEADD(day,@count,@firstDayOfMonth),101)

RETURN @outputdate

END

No comments:

Post a Comment