HeidiSQL Convert varchar into a Datetime

时间:2016-10-20 13:04:47

标签: mysql datetime varchar heidisql

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!

1 个答案:

答案 0 :(得分:0)

管理我自己想出一个解决方案,我想我会把它发布给其他需要帮助的人!

我做了CAST,然后使用HAVING进行过滤。它对我有用!

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