【问题标题】:Error inserting dates into my SQL Server table将日期插入我的 SQL Server 表时出错
【发布时间】:2018-09-21 17:37:05
【问题描述】:

我有一个名为TPatientVisits 的表,当我尝试插入日期时,我收到了这个错误。我不太确定为什么会出现错误我很确定我的日期格式正确,因为我在不同的表中使用相同的格式并且它们有效。

消息 241,第 16 级,状态 1,第 292 行
从字符串转换日期和/或时间时转换失败。

下面是我为表格插入的内容,谁能告诉我为什么这不起作用

INSERT INTO TPatientVisits (intPatientID, dtmVisit, intVisitTypeID, intWithdrawReasonID)
VALUES (1, '01/01/2017', 1, null),
       (1, '01/02/2017', 2, null),
       (1, '01/03/2017', 3, 3),
       (2, '02/02/2017', 1, null),
       (2, '02/03/2017', 2, null),
       (2, '02/04/2017', 3, 2),
       (3, '08/14/2017', 1, null),
       (3, '08//15/2017',  2, null),
       (3, '08//16/2017', 3, 6),
       (4, '12/12/2017', 1, null),
       (4, '12/13/2017', 2, null),
       (4, '12/14/2017', 3, 1),
       (5, '01/06/2017', 1, null),
       (5, '01/07/2017', 2, null),
       (5, '01/08/2017', 3, 5),
       (6, '06/06/2017', 1, null),
       (6, '06/07/2017', 2, null),
       (6, '06/08/2017', 3, 6),
       (7, '11/15/2017', 1, null),
       (7, '11/16/2017', 2, null),
       (7, '11/17/2017', 3, 2),
       (8, '11/16/2017', 1, null),
       (8, '11/17/2017', 2, null),
       (8, '11/18/2017', 3, 5),
       (9, '03/03/2017', 1, null),
       (9, '03/04/2017', 2, null),
       (9, '03/05/2017', 3, 4),
       (10, '08/08/2017', 1, null),
       (10, '08/09/2017', 2, null),
       (10, '08/10/2017', 3, 5)

【问题讨论】:

  • 看起来像 SQL Server。将日期格式设置为 '20170808' (YYYYMMDD) ISO-8601 格式与文化无关
  • 您在这些日期有双重//...,( 3, '08//15/2017', 2, null ) ,( 3, '08//16/2017', 3, 6 )

标签: sql-server date insert sql-insert sql-date-functions


【解决方案1】:

Wei 在上面 (+1'd) 中是正确的,因为将值插入日期列意味着这些值必须与日期格式兼容,并且 '08//15/2017' 和 '08//16/2017' 是不是。

因此,您必须检查硬编码的 VALUES 列表并确保所有日期都是日期。如果这些值是从表中选择的,那么使用 TRY_CAST 或 ISDATE() 将起作用,尽管我听说 ISDATE() 包含一些误报。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多