| Get Last Day of the Month Function | |||
CREATE FUNCTION [dbo].[ufn_GetLastDayOfMonth] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
DECLARE @vOutputDate DATETIME
SET @vOutputDate = CAST(YEAR(@pInputDate) AS VARCHAR(4)) + '/' +
CAST(MONTH(@pInputDate) AS VARCHAR(2)) + '/01'
SET @vOutputDate = DATEADD(DD, -1, DATEADD(M, 1, @vOutputDate))
RETURN @vOutputDate
END
GO
Description Here are the steps involved in getting the last day of the month as implemented in the user-defined function above:
| |||
Second Variant The second variant in getting the last day of the month implements the same algorithm as the first variant, which is to get the first day of the month for the given input date, add a month to that then subtract one day. The only difference with the second variant discussed below compared to the first variant is on how the first day of the month is derived. CREATE FUNCTION [dbo].[ufn_GetLastDayOfMonth] ( @pInputDate DATETIME )
RETURNS DATETIME
BEGIN
DECLARE @vOutputDate DATETIME
SET @vOutputDate = CAST(FLOOR(CAST(@pInputDate AS DECIMAL(12, 5))) -
(DAY(@pInputDate) - 1) AS DATETIME)
SET @vOutputDate = DATEADD(DD, -1, DATEADD(M, 1, @vOutputDate))
RETURN @vOutputDate
END
GO
Description In getting the first day of the month, this second variant did not make use of any date format. Instead, it made use of the decimal equivalent of the input date. The following outlines the logic behind this variant:
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:
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. |
Friday, October 5, 2012
Getting first and last month date using sql server
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment