Domanda

According to the MSDN documentation datetime2 has a range from 0001-01-01 to 9999-12-31. It also says that the ODBC string literal looks as follows:

{ 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.

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.
È stato utile?

Soluzione

According to 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 :

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.

I hope this helps!!!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top