Sql Function for Finding First Day of a Quarter

The code sample is a sql function that takes a DATETIME variable as input and returns a DATETIME variable too. The output denots the first day of the quarter the given date belongs to.

For example first day of the 3nd quarter of 2008 is (i.e quarter starting july) tuesday.



CREATE FUNCTION [dbo].[fn_Get_First_Day_Of_Qtr] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN

DECLARE @vOutputDate DATETIME

SET @vOutputDate = CAST(YEAR(@pInputDate) AS VARCHAR(4)) +
CASE WHEN MONTH(@pInputDate) IN ( 1, 2, 3) THEN '/01/01'
WHEN MONTH(@pInputDate) IN ( 4, 5, 6) THEN '/04/01'
WHEN MONTH(@pInputDate) IN ( 7, 8, 9) THEN '/07/01'
WHEN MONTH(@pInputDate) IN (10, 11, 12) THEN '/10/01'
END

RETURN @vOutputDate

END
GO


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: