代码之家  ›  专栏  ›  技术社区  ›  Ratha

将日期转换为日期时间会在SQL中产生错误

  •  0
  • Ratha  · 技术社区  · 7 年前

    我在一个 varchar(50) 具有以下值的列:

    1/01/2018
    

    我想将这些转换为日期时间值,例如: 2018-01-22 00:00:00.0000000

    我的SQL是类似的;

    select 
      [Site],
      CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
    from tableA;
    

    但我得到了;

    将varchar数据类型转换为datetime数据类型导致值超出范围。

    我也这样尝试过,但同样的错误;

    CONVERT(datetime, [InvDay]) as  Date,
    

    我怎样才能做到这一点?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    查看无法转换的值:

    select invday
    from tableA
    where try_cast(invday as date) is null and invday is not null;
    

    也不清楚您的格式是mm/dd/yyyy还是dd/mm/yyyy。可以使用指定格式 convert() :

    -- mm/dd/yyyy
    select invday
    from tableA
    where try_convert(date, invday, 101) is null and
          invday is not null;
    
    
    -- dd/mm/yyyy
    select invday
    from tableA
    where try_convert(date, invday, 103) is null and
          invday is not null;
    
        2
  •  0
  •   TomC    7 年前

    我想你想用 set dateformat dmy . 下面是一个例子:

    declare @d varchar(15) 
    set @d='13/1/2018'
    set dateformat dmy
    select convert(datetime,@d)