Quantcast
Viewing all articles
Browse latest Browse all 16

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

Good day danyeungw,

1. In your query you use CAST to convert the data type from string to DATETIME but you do not tell the server what is the style (the format) of the string. The server tries  to convert the string into DATETIME but it uses the default according to the session configuration since you did not gave him information regarding the style of the string

For example if you convert the string 01.02.2020 then what do you expect to get?
There are some styles which use the format dd.mm.yyyy which mean they will convert this into 2020-02-01
But other style might fit the format mm.dd.yyyy which returns 2020-01-02

SQL Server cannot read your mind (yet... maybe this will change in the future). Therefore, YOU MUST EXPLICITLY TELL THE SERVER WHAT IS THE FORMAT OF THE DATE!

Do not use CAST! Always use CONVERT and ALWAYS use style parameter
Check this link: https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017

Check the following query to get more understanding:

---------------------------------------------
SET DATEFORMAT dmy
SELECT cast('01.02.2020' as datetime)
-- 2020-02-01 00:00:00.000
SET DATEFORMAT mdy
SELECT cast('01.02.2020' as datetime)
-- 2020-01-02 00:00:00.000
GO
---------------------------------------------

 

2. You use CASE which has two options. If the condition fits then you convert the value into DATETIME but if the condition does not fit then you return the original value. Is the original value is type DATETIME?!? All returned options under the same CASE statement must return the same type! After all in the result SET all these will be in the same column.

For example, It make no sense to return INT for example in some rows but in other rows to return DATE. A table structure use the same type for all the values in the column.

* NULL is not a value, which is why you can sue NULL with different types. For example NULL can be in INT column or in VARCHAR column... In your case you must make sure that all values returned by the CASE statement are from the same data type.

Note! There is exception in SQL by using special dynamic type named sql_variant, but this is a different discussion :-)

**** As Jingyang Li said, please Post your table structure and get a better answer . If you provide queries to create your table then we will have the information about the structure of the table including the data type of your columns.


Image may be NSFW.
Clik here to view.
signature
  Ronen Ariely
 [Personal Site]    [Blog]    [Facebook]   [Linkedin]



Viewing all articles
Browse latest Browse all 16

Trending Articles