Conversion failed when converting date and/or time from character string while inserting datetime

后端 未结 15 1299
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 09:34

I was trying to create a table as follows,

create table table1(date1 datetime,date2 datetime);

First I tried inserting values as below,

15条回答
  •  隐瞒了意图╮
    2020-11-22 09:43

    Whenever possible one should avoid culture specific date/time literals.

    There are some secure formats to provide a date/time as literal:

    All examples for 2016-09-15 17:30:00

    ODBC (my favourite, as it is handled as the real type immediately)

    • {ts'2016-09-15 17:30:00'} --Time Stamp
    • {d'2016-09-15'} --Date only
    • {t'17:30:00'} --Time only

    ISO8601 (the best for everywhere)

    • '2016-09-15T17:30:00' --be aware of the T in the middle!

    Unseperated (tiny risk to get misinterpreted as number)

    • '20160915' --only for pure date

    Good to keep in mind: Invalid dates tend to show up with strange errors

    • There is no 31st of June or 30th of February...

    One more reason for strange conversion errors: Order of execution!

    SQL-Server is well know to do things in an order of execution one might not have expected. Your written statement looks like the conversion is done before some type related action takes place, but the engine decides - why ever - to do the conversion in a later step.

    Here is a great article explaining this with examples: Rusano.com: "t-sql-functions-do-no-imply-a-certain-order-of-execution" and here is the related question.

提交回复
热议问题