How to convert date to datetime?

Asked

Viewed 1,342 times

3

I have the following case, I’m trying to convert the one field date for datetime using the update

update tb_RHContratos
set DtCadastro = cast(DtCadastro as datetime)

But some of the date this does not format properly as are many record gets hard to identify which date is wrong.

I have the following msg error

Message 242, Level 16, Status 3, Line 13 The conversion of a type of date data in a type of datetime data resulted in a value outside the interval. The instruction has been completed

It has how to identify which date is out of range with a select or something?

  • What kind of DtCadastro?

  • I made an import of the mysql data to sqlserver, but need converts to datetime.

  • managed to find one of the wrong dates through the help of Excel and this in the format.. where DtCadastro = '1162-02-26'

  • @Gypsy . DtCadastro date

  • You can change the table, for example by adding columns?

  • @Ciganomorrisonmendez , adding columns yes , just could not change the type of this column

Show 1 more comment

1 answer

5


Use the command ISDATE to verify what cannot be converted:

SELECT *
FROM tb_RHContratos
WHERE isdate(DtCadastro) = 0

The tip I was going to give was to use datetime2, that supports very old dates, but this goes against what you want, which is precisely locating what is in trouble.


EDIT

There’s one more function you can use: TRY_CAST.

SELECT DtCadastro, 
    CASE WHEN TRY_CAST(DtCadastro AS datetime) IS NOT NULL 
    THEN 'Ok'
    ELSE 'Falhou'
AS "Resultado da Conversão"
FROM tb_RHContratos
  • returned me the error ... Message 8116, Level 16, State 1, Line 18 Invalid date data type for argument 1 of the isdate function.

  • I found the answer in the link => [https://msdn.microsoft.com/pt-br/library/ms187819(v=sql.120). aspx], date type accepts old date already datetime not so the error value outside the range, the itervalor is January 1, 1753, to December 31, 9999

  • the TRY_CAST is from sql server 2008 ?

  • No, it works from 2012.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.