如何在SQL中的DATEFROMPARTS中使用计算值

时间:2019-07-09 18:07:09

标签: tsql date

我需要DATEFROMPARTS函数中的计算月份值。该月必须比CURRENT_TIMESTAMP月早七个月。

这是我尝试过的:

DATEFROMPARTS(Year(CURRENT_TIMESTAMP),Month(CURRENT_TIMESTAMP)-7,1)as SevenMoAgo;

I will eventually use this in the following expression where '12-01-2018' is:

where RECORDED_SERVICE_STARTTIME > ='12-01-2018'

I later used

declare @CurMo AS INT;
declare @MonPri7 AS INT;
set @CurMo = Month(CURRENT_TIMESTAMP);
set @MonPri7 = (@CurMo -7);
Datefromparts(Year(CURRENT_TIMESTAMP), @MonPri7, 1) as SevenMoAgo;

这也不起作用。

我收到以下错误消息:

“无法构造数据类型日期,某些参数的值无效。”

对于第二个代码,我得到:

第8级第1行第8行102消息 'Datefromparts'附近的语法不正确。

2 个答案:

答案 0 :(得分:0)

原因是@MonPri7 is equal to ZERO when you say (@CurMo -7)

有许多不同的计算方法,但是,如果您要修正逻辑,则应使用此方法:

declare @CurMo AS INT;
declare @MonPri7 AS INT;
set @CurMo = Month(CURRENT_TIMESTAMP);
set @MonPri7 = (@CurMo -7);
declare @Y int = Year(CURRENT_TIMESTAMP) -- <-- This is new variable
-- if 7 months ago is ZERO then you should go back to prev year December
if @MonPri7 = 0
begin
  set @MonPri7 = 12
  set @Y = @Y - 1
end

编辑:

declare @SevenMonthsAgo datetime;
select @SevenMonthsAgo = Datefromparts(@Y, @MonPri7, 1);

SELECT yourfields
FROM yourtable
where RECORDED_SERVICE_STARTTIME > = '01-01-2019' and
      RECORDED_SERVICE_STARTTIME > = @SevenMonthsAgo

答案 1 :(得分:0)

尝试一下...

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - 7, 0)

让我解释一下。首先,我们需要了解SQL Server interprets 0 as 1900-01-01,如以下DATEPART函数所示。

SELECT DATEPART(YEAR, 0)  AS Year
     , DATEPART(MONTH, 0) AS Month
     , DATEPART(DAY, 0)   AS Day;

哪个返回...

Year        Month       Day
----------- ----------- -----------
1900        1           1

因此,我的SQL可以重写为...

SELECT DATEADD(MONTH, DATEDIFF(MONTH, '1900-01-01', CURRENT_TIMESTAMP) - 7, '1900-01-01')

现在,也许可以更容易地了解这里发生的情况。 DATEDIFF函数返回从1900-01-01到今天(CURRENT_TIMESTAMP)之间的月份数1434。

SELECT DATEADD(MONTH, 1434 - 7, '1900-01-01')

然后,我们从1434中减去7,即1427,然后再加上许多个月回到1900-01-01。

SELECT DATEADD(MONTH, 1427, '1900-01-01')

产量为2018-12-01。