为什么getdate返回1 \ 1 \ 1900

时间:2017-04-01 20:20:13

标签: sql-server tsql

我有以下代码,如果星期六或星期日将日期移动到星期五,但为什么它会返回1900-01-06 00:00:00.000而不是2017-03-31 13:18:12.300我尝试了它getdate() - 1工作正常,这是星期五效果很好。我觉得为什么周六或周日我不工作?

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()

select 
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 5
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

上面的代码1900-01-06 00:00:00.000

---- getdate() - 1 ------

set datefirst 7 --Sunday

declare @ACUTBY datetime = getdate()-1

select 
case datepart(WEEKDAY, @ACUTBY)
    when 1 then 2
    when 7 then 5
    else  @ACUTBY
end as [A-CUT BY]

上面的代码返回2017-03-31 13:18:12.300

2 个答案:

答案 0 :(得分:1)

尝试select Cast( 5 as DateTime )

您正在混合数据类型,例如整数5和日期时间@ACUTBYcase的结果必须是单个数据类型。因此,数字将转换为DateTime。由于DateTime的基准日期是1900年1月1日,因此在1月6日添加5结果。

您可能需要以下内容:

declare @Samples as Table ( Sample Date );
insert into @Samples ( Sample ) values
  ( '20170402' ), ( '20170403' ), ( '20170404' ),
  ( '20170405' ), ( '20170406' ), ( '20170407' ), ( '20170408' );

select Sample, DatePart( dw, Sample ) as DoW,
  case DatePart( dw, Sample )
    when 1 then DateAdd( day, -2, Sample )
    when 7 then DateAdd( day, -1, Sample )
    else Sample end as WeekDay
  from @Samples;

答案 1 :(得分:0)

您正尝试合并两个不同的返回值。

select 
case when datepart(WEEKDAY, @ACUTBY) = 1 then 2
     when datepart(WEEKDAY, @ACUTBY) = 7 then 5
     else datepart(WEEKDAY, @ACUTBY)
end as [A-CUT BY]