需要更改以下代码才能获得上个月的第一天(2016年7月1日)和当前的第一天:
DECLARE @StartDate as Date = (SELECT cast(Dateadd(D, -(day(getdate()) - 1), getdate()) as date))
DECLARE @EndDate as Date = (SELECT dateadd(M,1,cast(Dateadd(D, -(day(getdate()) - 1), getdate()) as date)))
DECLARE @EndDate2 as Date = (SELECT cast(getdate() as date))
答案 0 :(得分:0)
首先获取当月的第一个月份,然后使用该值获取前一个月的第一个日期:
DECLARE @Current DATE = CAST(DATEADD(MM,DATEDIFF(MM,0,GETDATE()),0) AS DATE)
DECLARE @Prior DATE = CAST(DATEADD(MM,-1,@Current) AS DATE)
答案 1 :(得分:0)
更改代码中的前两行:
DECLARE @StartDate as Date = (SELECT cast(Dateadd(D, -(day(getdate()) - 1), getdate()) as date))
DECLARE @EndDate as Date = (SELECT dateadd(M,1,cast(Dateadd(D, -(day(getdate()) - 1), getdate()) as date)))
为:
DECLARE @StartDate as Date = (SELECT DATEADD(mm, DATEDIFF(mm,0,getdate())-1, 0));
DECLARE @EndDate as Date = (SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0));
说明:
DATEDIFF(mm,0,getdate()), 0)
获取纪元与当前日期之间的差异。 DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))
只是将这些月份再次添加到纪元。