根据参数值获取前两个月的日期

时间:2011-10-10 05:20:07

标签: sql tsql

我在存储过程中有一个datetime参数值,它将获得类似'30 -Sep-2011'的值,并且该值将始终是该月的最后一天!我如何根据收到的价值获得前两个月的日期?价值观也必须是一个月的最后一天!

3 个答案:

答案 0 :(得分:1)

declare @TwoMonthsBack datetime 

select @TwoMonthsBack= dateadd(dd,-1, DateAdd(MM,-2,DateAdd(dd,1,@YourInputDateParam)))

示例:

declare @YourInputDateParam datetime = '30-Sep-2011'
declare @TwoMonthsBack datetime 
select @TwoMonthsBack= dateadd(dd,-1, DateAdd(MM,-2,DateAdd(dd,1,@YourInputDateParam)))

SELECT @TwoMonthsBack

打印:

2011-07-31 00:00:00.000

说明:

取输入日期(始终是指定的最后一天);添加一天(将使下个月的第一天 - 例子中的10月1日);减去2个月(将从输入日期 - 例如8月1日的1个月前的第一天);减去1天(将从输入日期 - 例如7月31日的2个月前的最后一天)

答案 1 :(得分:1)

查询:

DECLARE @LastDay DATETIME;

SELECT @LastDay = '2011-02-28';
-- Previous two months "anatomy"
SELECT  @LastDay AS LD
        ,CONVERT(DATETIME, 0) AS ["Day zero"]
        ,DATEDIFF(MONTH, 0, @LastDay) AS [Months from "Day zero"]
        ,DATEDIFF(MONTH, 0, @LastDay)-(2-1) AS [Months from "Day zero" - 1 month = previous month]
        ,DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, @LastDay)-1, 0)) AS LDPrevious2Months;
-- End of "anatomy"

SELECT @LastDay = '2011-03-31';
SELECT  @LastDay AS LD
        ,DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, @LastDay)-1, 0)) AS LDPrevious2Months;

SELECT @LastDay = '2011-04-30';
SELECT  @LastDay AS LD
        ,DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, @LastDay)-1, 0)) AS LDPrevious2Months;

结果:

LD                      "Day zero"              Months from "Day zero" Months from "Day zero" - 1 month = previous month LDPrevious2Months
----------------------- ----------------------- ---------------------- ------------------------------------------------- -----------------------
2011-02-28 00:00:00.000 1900-01-01 00:00:00.000 1333                   1332                                              2010-12-31 23:59:59.997


LD                      LDPrevious2Months
----------------------- -----------------------
2011-03-31 00:00:00.000 2011-01-31 23:59:59.997


LD                      LDPrevious2Months
----------------------- -----------------------
2011-04-30 00:00:00.000 2011-02-28 23:59:59.997

答案 2 :(得分:0)

declare @start_date datetime
--declare @start_date1 datetime
declare @end_date datetime
--set @start_date1 =(select DATEDIFF(mm,GETDATE() ,getdate()))
set @start_date =(select DATEADD (mm,-10,getdate()))

set @end_date = (select convert(varchar(20),GETDATE()))
print @end_date
print @start_date