【问题标题】:Conversion failed when converting date and/or time from character string. date not accepting从字符串转换日期和/或时间时转换失败。日期不接受
【发布时间】:2020-12-21 17:01:26
【问题描述】:

传递日期参数时出现存储过程执行错误

create procedure emp_leave_from_to
    @emp_code int,
    @leave_from_date date ,
    @leave_to_date date
as
begin 
    create table #employee_leave
    (
         emp_code varchar (100),
         emp_name varchar (100),
         emp_department varchar(50),
         leave_from_date date
    )

    insert into #employee_leave (emp_code, leave_from_date)
        select employee_code, leave_from_date
        from emp_leave
        where leave_from_date between @leave_from_date and @leave_to_date

    update temp 
    set temp.emp_name = a.employee_name,
        temp.emp_department = a.dept
    from #employee_leave temp, employee a
    where a.employee_code = temp.emp_code
end 

exec emp_leave_from_to 1,'01/01/2016','21/12/2020' 

我收到此错误:

从字符串转换日期和/或时间时转换失败

【问题讨论】:

  • (1) 不要将日期存储为字符串... (2) 错误发生在哪里,在哪一行? (3) 服务器的区域格式是什么? (4) 您是否认为,即使转换确实有效,dd/mm/yyyy 格式字符串也会按照您真正想要的方式排序?再次参见#1。
  • 不要对日期使用模棱两可的格式,也不要对数据类型使用varchar。有一个 date 数据类型是有原因的,并使用 yyyyMMddyyyy-MM-ddThh:mm:ss.nnnnnn 作为您的文字字符串日期。
  • 我在日期和日期时间都试过了
  • Bad habits to kick : using old-style JOINs - 旧式 逗号分隔的表格列表 样式已替换为 ANSI 中的 proper ANSI JOIN 语法-92 SQL 标准(25 多年前),不鼓励使用它
  • 那么问题也出在你的数据库上,你愚蠢地将日期和时间数据存储在varchar中。只有一个真正的解决方案;修复你的设计。

标签: sql-server datetime


【解决方案1】:

我相信你的问题就在这里。

exec emp_leave_from_to 1,'01/01/2016','21/12/2020' 

当您指定日期常量时,您需要在ISO-8601 date format 中将它们作为文本字符串提供,就像这样。

exec emp_leave_from_to 1,'2016-01-01','2020-12-21' 

此格式布局为YYYY-mm-dd。它对国际发行的软件有很大的好处,它避免了美国和其他地方不同日期约定引入的mm/dd/YYYYdd/mm/YYYY 之间的歧义。

【讨论】:

    【解决方案2】:

    问题在于您传递给存储过程的日期值。

    您正在尝试传入'21/12/2020'

    SQL Server 试图将其解析为日期,认为其格式为 'MM/dd/yyyy',但您传入的是 'dd/MM/yyyy'

    最好使用的格式是'yyyy-MM-dd'

    例如,重现您的问题:

    SELECT CONVERT(date, '21/12/2020')
    

    返回:

    Msg 241, Level 16, State 1, Line 1
    Conversion failed when converting date and/or time from character string.
    

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多