简体   繁体   中英

HeidiSQL Convert varchar into a Datetime

I've inherited a database that has varchars instead of datetimes and I want to be able to do some reporting that says if one date is less than another.

I have this database query:

Select 
    RENEWDATE, 
    (CONCAT(substring(renewdate, 1,4), "-", substring(renewdate, 5,2), "-", substring(renewdate, 7,2), " 23:59:59")) 
FROM solutionsdmp 
WHERE  Approval = "Approved" 
GROUP BY Author 
ORDER BY  Author ASC

Which converts this date format: 20160217 into this: 2016-02-17 23:59:59

I have two dates a last modififed and a renew date. They're both stored as varchars but in different formats. One is stored as a varchar but formatted like a datetime 2015-02-17 23:59:59 and then the other as listed above is shown as 20160217 . I want to be able to convert them both to datetimes so that I can run a query and check whether one is less than the other. So that I can see whether or not the renewal date has passed.

I've tried a lot of variations that aren't working, but this is my latest attempt:

    SELECT 
        RENEWDATE, 
        CONVERT(DATETIME,(CONCAT(substring(renewdate, 1,4), "-", substring(renewdate, 5,2), "-", substring(renewdate, 7,2), " 23:59:59"))) 
    FROM solutionsdmp 
    WHERE  Approval = "Approved" 
    GROUP BY Author 
    ORDER BY  Author ASC

Can someone point me in the right direction?

Thanks!

Managed to come up with a workaround solution on my own, thought I'd post it here for anyone else who needs the help!

I did a CAST and then used HAVING to do my filtering on. It worked for me!

Select 
     Author, 
     Problem,
     CAST(Last_Modified_DATE AS DATETIME) AS lmd, 
     CAST((CONCAT(substring(renewdate, 1,4), "-", substring(renewdate, 5,2), "-", substring(renewdate, 7,2), " 23:59:59")) AS DATETIME) AS rend
from solutionsdmp
WHERE Approval = "Approved"
HAVING 
lmd < rend
order by 
Author ASC

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