为什么mssqlserver在插入第二行而不是第一行时出错?

iq3niunx  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(371)

我有一个sql表,它允许我插入一些带有datetime字段的行,但不是所有的行,我不明白为什么不插入。我得到的错误是
'将varchar数据类型转换为datetime数据类型导致值超出范围。'
为了解决这个问题,我创建了一个带有1列的临时表,并尝试添加导致这个问题的两个日期时间。 create table #DateTimeTest ( created datetime ); 然后我试着插入这两行

insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12 05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');

第一行是插入没有任何问题,第二行错误,但我不明白为什么。

(1 row affected)
Msg 242, Level 16, State 3, Line 10
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

Completion time: 2020-07-15T11:28:43.6451779+01:00
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
ej83mcc0

ej83mcc01#

显然,你的日期格式是ydm而不是ymd。你可以用几种方法来解决这个问题。
一种方法是使用明确的日期/时间格式。对你来说,这包括 T :

insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12T05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19T05:31:00.00');

之所以这样做是因为yyyy-mm-ddthh:mi:ss format是sql server中日期/时间格式的标准格式—明确且不受 dateformat . 类似地,yyyymmdd(注意:没有连字符)是sql server中日期常量的标准、明确的格式,但yyyy mm dd受 dateformat .
第二种方法是设置 dateformat 致ymd:

set dateformat YMD;

这里有一把小提琴来说明这一点。
第三种方法是使用诸如 convert() --也许还有一些字符串操作。

相关问题