Today is month end (30 September 2013) and I was checking my general checklist for month end closing procedure. I saw one of my scripts that I had written earlier regarding how to check whether a date is month end date or not. So, I thought of re-writing this script even much shorter & efficient than my earlier script using EOMONTH .
Let me create a sample table to demonstrate.
USE tempdb GO --DROP TABLE tbl_Sample --GO CREATE TABLE tbl_Sample ( [ID] INT, [Date] DATETIME ) GO INSERT INTO tbl_Sample VALUES (1,'2013-01-01') INSERT INTO tbl_Sample VALUES (2,'2013-03-31') INSERT INTO tbl_Sample VALUES (3,'2013-10-10') INSERT INTO tbl_Sample VALUES (4,'2013-12-31') GO
SOLUTION 1 :
Given below is the script that we usually use in SQL Server 2005/2008 to check whether the date is End of month date or not.
--This script is compatible with SQL Server 2005 and above. USE tempdb GO SELECT [ID],[Date], (CASE WHEN CONVERT(varchar(11) ,DATEADD(MONTH, DATEDIFF(MONTH, 0, [Date])+1, -1),120)=[Date] THEN 'Month End' ELSE 'Not a Month End' END) As [Result] FROM tbl_Sample GO
SOLUTION 2 :
Given below is the script, that I developed using new functions (EOMONTH & IIF) shipped in SQL Server 2012 to check whether the date is End of month date or not. Due to these functions, we can reduce the script size and improve the performance.
--This script is compatible with SQL Server 2012 and above. USE tempdb GO SELECT [ID],[Date], IIF(EOMONTH([Date])=[Date],'Month End','Not a Month End') As [Result] FROM tbl_Sample GO --OUTPUT
CONCLUSION :
As you can see, both solutions have the same result set but Solution 2 is recommended because it is using only one function to check whether the date is month end date or not, instead of a lot of date functions.
Solution 1 is long, you can simple use
(CASE WHEN DAY([Date]+1)=1
THEN ‘Month End’ ELSE ‘Not a Month End’ END) As [Result]
Hi Harsh,
Very nice solution, but usually I recommend date to be added using DateAdd function.
Thanks
Imran
Thanks