Tag Archives: dates

T-SQL Create a View for Report Date Ranges by Month

The below example gives prior and current month first and last day values.The code below dynamically formats the date to give you date range values for reporting:

[LFM-FirstDay] – First Day of thePrior Month or Last Full Month First Day,
[LFM-LastDay] – 11:59 PM of the last day of the prior month,
[CM-FirstDay] – Current Month First Day and
[CM-LastDay] – 11:59 PM of the last day of the Current month.

USE [dbofchoice]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [DBO].[ReportDates]
AS
/*
LFM = LAST FULL MONTH
CM = CURRENT MONTH
*/
SELECT
DATEADD(month, -1 ,DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0))
as [LFM-FirstDay]
,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate()),0))
as [LFM-LastDay]
,DATEADD(mm, DATEDIFF(m,0,getdate()),0)
as [CM-FirstDay]
,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,getdate())+1,0))
as [CM-LastDay]
GO