Second Variant
Not many SQL Server users are aware that when converting a date string into a
DATETIME data type, if the DAY part of the date is not specified, SQL Server
will automatically assign the value of 1 for the day. Given this, if you
try to CAST the date string "2005 JAN" to a DATETIME data type with the DAY
part not specified, SQL Server will convert this to "2005-01-01".
The following version of the user-defined function makes use of this feature of
SQL Server wherein if the DAY part is not specified in a date string, a value
of 1 is automatically assigned.
CREATE FUNCTION [dbo].[ufn_GetFirstDayOfQuarter] ( @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 'JAN'
WHEN MONTH(@pInputDate) IN ( 4, 5, 6) THEN 'APR'
WHEN MONTH(@pInputDate) IN ( 7, 8, 9) THEN 'JUL'
WHEN MONTH(@pInputDate) IN (10, 11, 12) THEN 'OCT'
END
RETURN @vOutputDate
END
GO
Third Variant
Here's yet another version of the user-defined function that makes use of
DATEPART date function with a parameter of "Q" to get the Quarter of the input
date instead of the MONTH function. This version still makes use of the
feature of the missing DAY part and simply concatenates the YEAR and first
month of the quarter.
CREATE FUNCTION [dbo].[ufn_GetFirstDayOfQuarter] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
DECLARE @vOutputDate DATETIME
SET @vOutputDate = CAST(YEAR(@pInputDate) AS VARCHAR(4)) + ' ' +
CASE DATEPART(Q, @pInputDate)
WHEN 1 THEN 'JAN'
WHEN 2 THEN 'APR'
WHEN 3 THEN 'JUL'
WHEN 4 THEN 'OCT'
END
RETURN @vOutputDate
END
GO