简体   繁体   English

SQL Server datetime2和ODBC

[英]SQL Server datetime2 and ODBC

According to the MSDN documentation datetime2 has a range from 0001-01-01 to 9999-12-31 . 根据MSDN文档, datetime2的范围是0001-01-019999-12-31 It also says that the ODBC string literal looks as follows: 它还说ODBC字符串文字如下所示:

{ ts 'yyyy-mm-dd hh:mm:ss[.fractional seconds]' }

Why do the last three statements fail? 为什么最后三个语句失败了? They only succeed when the value is larger than 1753-01-01 and the ODBC syntax is not used. 它们仅在值大于1753-01-01且未使用ODBC语法时才会成功。

CREATE TABLE Book (Id INTEGER IDENTITY NOT NULL, ReleasedOn DATETIME2)

INSERT INTO Book VALUES ('0001-01-01 00:00:00')
INSERT INTO Book VALUES ('0501-01-01 00:00:00')
INSERT INTO Book VALUES ('1752-12-31 00:00:00')
INSERT INTO Book VALUES ('1753-01-01 00:00:00')
INSERT INTO Book VALUES ('1902-09-17 00:00:00')


SELECT * FROM Book WHERE ReleasedOn = {ts '1753-01-01 00:00:00'} -- OK
SELECT * FROM Book WHERE ReleasedOn = {ts '1902-09-17 00:00:00'} -- OK

SELECT * FROM Book WHERE ReleasedOn = '0001-01-01 00:00:00' -- OK
SELECT * FROM Book WHERE ReleasedOn =' 0501-01-01 00:00:00' -- OK
SELECT * FROM Book WHERE ReleasedOn = '1752-12-31 00:00:00' -- OK

SELECT * FROM Book WHERE ReleasedOn = {ts '0001-01-01 00:00:00'} -- Error
SELECT * FROM Book WHERE ReleasedOn = {ts '0501-01-01 00:00:00'} -- Error
SELECT * FROM Book WHERE ReleasedOn = {ts '1752-12-31 00:00:00'} -- Error

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

According to MSDN : 根据MSDN

SQL Server always treats ODBC data as being of the datetime data type.
*Conversion Notes*
1.ODBC string literals are mapped to the datetime data type. Any assignment 
  operation from ODBC DATETIME literals into date, time, datetime2, or datetimeoffset
  types will cause an implicit conversion between datetime and these types as 
  defined by the conversion rules.

and Date range for Datetime datatype is : Datetime数据类型的日期范围是:

January 1, 1753, through December 31, 9999

so that's the reason why SQL server throws an error when ODBC string literal is used in last 3 statements, because there it does an implicit conversion to datatype Datetime and not Datetime2 and values supplied are out of range values possible for Datetime datatype hence the error. 这就是为什么SQL服务器在最后3个语句中使用ODBC字符串文字时抛出错误的原因,因为它对数据类型Datetime而不是Datetime2了隐式转换,并且提供的值超出了Datetime数据类型可能的范围值,因此出现了错误。

I hope this helps!!! 我希望这有帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM