Third Variant
The third variant in getting the last day of the month for the given input date
simply simplifies the code by putting the step in getting the first day of the
month into a separate function, called here as
[dbo].[ufn_GetFirstDayOfMonth].
CREATE FUNCTION [dbo].[ufn_GetLastDayOfMonth] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
DECLARE @vOutputDate DATETIME
SET @vOutputDate = DATEADD(DD, -1, DATEADD(M, 1,
[dbo].[ufn_GetFirstDayOfMonth] (@pInputDate)))
RETURN @vOutputDate
END
GO
Description
Just like the previous two variants, this variant simply gets the first day of
the month for the given input date, add 1 month to it and subtract 1 day.
Here's a summary of the steps performed by this user-defined function:
-
[dbo].[ufn_GetFirstDayOfMonth] (@pInputDate)
- The first step calls the user-defined function that gets the first day of the
month given the input date.
-
DATEADD(M, 1, @FirstDayOfMonth)
- The next step is to get the first day of the following month.
-
DATEADD(DD, -1, @FirstDayOfNextMonth) - Lastly, given the first day of
the following month, 1 day is subtracted from it to get the last day of the
month.
Usage
Here's an example SELECT statement that uses this user-defined function and yet
another function, the [dbo].[ufn_GetFirstDayOfMonth], which gets the first day
of the month given an input date.
SELECT * FROM [dbo].[Employees]
WHERE [BirthDate] BETWEEN [dbo].[ufn_GetFirstDayOfMonth] ( GETDATE() ) AND
[dbo].[ufn_GetLastDayOfMonth] ( GETDATE() )
This SQL statement will retrieve all employees whose birthday falls within the month.