You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress/tedious/mssql:日期时间字符串转换失败问题求助

解决思路:Conversion failed when converting date and/or time from character string

针对遇到的问题,以下是具体排查和解决步骤:

  • 确认字段实际类型
    先在SQL Server中执行以下语句,检查hd_date字段的真实数据类型:

    sp_help 'holidays'
    

    如果字段类型是varchar而非date/datetime,使用year()函数会触发隐式转换,一旦表中存在格式错误的字符串就会报错。

  • 显式转换日期字段(适配Cypress插件)
    即使字段是日期类型,Cypress的sqlServer插件可能在解析日期时出错,可在查询时显式将日期转为字符串:

    select convert(varchar, hd_date, 23) as hd_date, hd_name from holidays
    

    其中23对应yyyy-MM-dd格式,和数据格式匹配,避免插件自动解析时的转换错误。

  • 调整Cypress插件配置
    检查cypress-sql-server插件的配置,在cypress.json(或cypress.config.js)中添加日期处理配置,强制将日期字段转为字符串返回:

    {
      "db": {
        "user": "your_user",
        "password": "your_password",
        "server": "your_server",
        "options": {
          "database": "your_db",
          "encrypt": true,
          "dateStrings": true
        }
      }
    }
    
  • 排查脏数据
    若hd_date是字符串类型,执行以下语句查找格式错误的记录:

    select hd_date from holidays where isdate(hd_date) = 0
    

    清理或修正这些不符合日期格式的记录,避免转换报错。

  • 优化WHERE条件写法
    如果hd_date是字符串类型,避免直接用year()函数(会导致全表扫描),改用前缀匹配或显式转换:

    -- 前缀匹配(推荐,可利用索引)
    select hd_name from holidays where hd_date like '2025-%'
    
    -- 显式转换后取年份
    select hd_name from holidays where year(convert(date, hd_date, 23)) = 2025
    

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 10:22:17