向表中插入日期值时出现 SQL 错误:字符串转换失败

问题描述 投票:0回答:2

我在尝试将数据插入 SQL 表(特别是 DATE 列)时遇到错误。日期格式为 YYYY-MM-DD(例如 2010-01-12),但我不断收到转换错误。

这是错误消息:

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

相关表(BOOK)的结构如下:

BookName (PK, VARCHAR(45), not null)
Genre (VARCHAR(25), not null)
DateOfPublication (DATE, not null)
NoOfPages (INT, not null)
WriterID (PK, FK, VARCHAR(11), not null)
EditorID (FK, VARCHAR(11), not null)

这是导致错误的插入语句之一的示例:

INSERT INTO BOOK (BookName, Genre, DateOfPublication, NoOfPages, WriterID, EditorID)
VALUES ('Valley of Heroes', 'Fiction', '2010-01-12',

我尝试了不同的日期格式,但仍然遇到相同的错误。

我应该如何正确格式化插入查询中的 DateOfPublication 字段以符合 SQL DATE 类型?

sql sql-server ssms date-formatting
2个回答
1
投票

您的值列表中似乎有错误。 值“10”应该在末尾..

你的陈述

insert into BOOK (BookName, Genre, DateOfPublication, NoOfPages, WriterID, EditorID)
values ('Valley of Heroes','10','Fiction','2010-01-12',874,'20');

会尝试将值“小说”添加到“发布日期”列中。

要纠正它,请使用

insert into BOOK (BookName, Genre, DateOfPublication, NoOfPages, WriterID, EditorID)
values ('Valley of Heroes','Fiction','2010-01-12',874,'10','20');

1
投票
当您执行

insert 时,

始终
列出列。列名和值的顺序必须相同:

insert into book (BookName, WriterID, Genre, DateOfPublication, , NoOfPages, EditorID)
    values ('Valley of Heroes', '10', 'Fiction', '2010-01-12', 874, '20');
© www.soinside.com 2019 - 2024. All rights reserved.