Return null for date_format when input is null in

2019-02-22 01:30发布

I'm doing something like this:

SELECT date_format(mydate, '%d/%m/%Y') FROM xyz;

When mydate is NULL, date_format returns 00/00/0000. This is correct, but how can I make it so that it returns NULL when the input is NULL?

4条回答
Evening l夕情丶
2楼-- · 2019-02-22 02:24

You can wrap this into a IF-Clause, like this:

SELECT IF(mydate,DATE_FORMAT(mydate, '%d/%m/%Y'),NULL) FROM xyz;

That said, if your variable mydate is not a date value, the query in your post should return (NULL) anyway.

查看更多
Summer. ? 凉城
3楼-- · 2019-02-22 02:24
case 
    when date_format(mydate, '%d/%m/%Y') = 00/00/0000 then null
    else ///
end as mydate,
查看更多
何必那么认真
4楼-- · 2019-02-22 02:36
SELECT IF(mydate,date_format(mydate, '%d/%m/%Y'),NULL) FROM xyz;

Source: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

查看更多
太酷不给撩
5楼-- · 2019-02-22 02:37
select case when isnull(mydate) then null else date_format(mydate, '%d/%m/%Y') end as mydate from xyz;
查看更多
登录 后发表回答