Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert INT to DATETIME (SQL)

I am trying to convert a date to datetime but am getting errors. The datatype I'm converting from is (float,null) and I'd like to convert it to DATETIME.

The first line of this code works fine, but I get this error on the second line:

Arithmetic overflow error converting expression to data type datetime.

CAST(CAST( rnwl_efctv_dt AS INT) AS char(8)), CAST(CAST( rnwl_efctv_dt AS INT) AS DATETIME), 
like image 836
Daniel Avatar asked Oct 04 '10 13:10

Daniel


People also ask

Can we convert integer to date in SQL?

The method will convert the integer value into dd/MM/yyyy format by extracting dd, MM, and yyyy parts separately using arithmetic operation and add / between MM and yyyy parts. It is then converted into VARCHAR datatype. CONVERT function with style 103 is used to convert the formatted string into a proper date value.

How do I convert text to date in SQL?

SQL Server: Convert string to date explicitly In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.

Can you convert date to datetime in SQL?

We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.


2 Answers

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt )) 

here are some examples

select CONVERT (datetime,5) 

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101) 

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int select @i = 20100101 select CONVERT (datetime,convert(char(8),@i)) 
like image 104
SQLMenace Avatar answered Sep 20 '22 23:09

SQLMenace


Try this:

select CONVERT(datetime, convert(varchar(10), 20120103)) 
like image 36
rchacko Avatar answered Sep 20 '22 23:09

rchacko