简体   繁体   中英

Convert decimal to date format SQL

I am trying to convert a column FC_FROM_DATE containing decimal values (ex. 20,200,721) into a date format 2020/07/21.

I have tried this code

SELECT TO_DATE(CHAR(CAST(FC_FROM_DATE AS DECIMAL(8,0))), 'YYYY/MM/DD') 
FROM MARKETS.FORECAST

I get an error

Argument for chr should be between 0 and 127

Would much appreciate your help!

If you are using Oracle then you can use the following query:

SELECT TO_DATE(CAST(FC_FROM_DATE AS VARCHAR(8), 'YYYY/MM/DD') FROM Table

Seeing as the persisted format is YYYYMMDD you could convert the value to a varchar(8) and then use CONVERT to get a Date instance.

SELECT CONVERT(DATE, CAST(FC_FROM_DATE AS VARCHAR(8))) FROM MARKETS.FORECAST

Ideally Dates are stored as Date and a Date with a time component is stored as DATETIME2 (or equivalent if not Sql Server).

Test of the code above

DECLARE @FC_FROM_DATE decimal(8,0) =  20200721
SELECT CONVERT(DATE, CAST(@FC_FROM_DATE AS VARCHAR(8)))

2020-07-21

Disclaimer: This works in MS Sql Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM