SELECT DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, GETDATE())+1, 0))
To me, this is simply ridiculous. First of all, there's so many nested functions in this query that I can't keep them all straight. Next, there's NO way you can remember it all to plug in to a query at any given moment (was this a +1 or a -1 at this spot??). So, below is some code to create two user defined functions that will return either the first day of the month or the last day of the month of any given date passed to the function.
First Day of Month:
USE [son_db] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[udfFirstDayOfMonth] ( @startDate DATETIME ) RETURNS DATETIME AS BEGIN RETURN DATEADD(mm, DATEDIFF(mm,0,@startDate), 0) ENDLast Day of Month:
USE [son_db] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE FUNCTION [dbo].[udfLastDayOfMonth] ( @startDate DATETIME ) RETURNS DATETIME AS BEGIN RETURN DATEADD(ms,-3,DATEADD(mm, DATEDIFF(m,0,@startDate)+1, 0)) ENDTo use the user defined functions, simply pass a date to the function as a variable in your SELECT statement.
SELECT dbo.udfFirstDayOfMonth(GETDATE()) --First date of this month SELECT dbo.udfFirstDayOfMonth(GETDATE()-5) --First date of the month 5 days prior to todayThis should make using beginning and ending dates of months a bit easier for you.
No comments:
Post a Comment