Error when conversion of a varchar data type to a datetime

Ramana Kopparapu 306 Reputation points
2023-12-07T15:01:17.4966667+00:00

Hi,

I have column NMDT decimal(8,0) - In one table

Last_Date datetime2(7) - In another table

wants to convert NMDT (decimal) column as Last_Date (Datetime2). I write below query but getting error message.

CASE WHEN NMDT = 0 THEN NULL ELSE CONVERT(DATETIME, CAST(NMDT AS VARCHAR(10)) + STUFF(STUFF(STUFF(right('000000'+ CAST(NMDT AS VARCHAR(10)), 6), 1, 0, ' '), 4, 0, ':'), 7, 0, ':')) END  AS Last_Date,

Error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Please assist me.

Thanks in advance.

SQL Server Other
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2023-12-08T06:44:15.4+00:00

    varchar data type to a datetime data type resulted in an out-of-range value.

    Datetime has a range between year 1753 and 9999; you must have date values below 1753.

    Use the data type date or datetime2, see

    https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-types-transact-sql?view=sql-server-ver16

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.