SQL possible to display (only display) a non-date string in a date column?
I wondered if its possible to show a "-" whenever there is no date in a date column?
So one tuple might be {Dave, 13th July 2011}, whereas another could be {John,-}
EDIT: Thanks to the person below who suggested this:
SELECT `ID`, COALESCE(CAST(开发者_如何学JAVA`Graduation Date` AS CHAR), '-') FROM <table>
It worked!
Use COALESCE
?
SELECT name, COALESCE(date, '-')
FROM table
EDIT: Don't see how it is possible that it doesn't work. Example:
SELECT COALESCE('2011-01-01', '-') //returns '2011-01-01'
SELECT COALESCE('', '-') //returns ''
SELECT COALESCE(NULL, '-') //returns '-'
Try them 3 statements and you will see what is returned.
EDIT2:
SELECT name, IF(COALESCE(date, '-') = '', '-', date)
FROM table
If your date column contains some special dates that you would like to treat in the same way as NULLs (for example, 0000-00-00
), you could try this method:
SELECT COALESCE(NULLIF(yourdatecolumn, '0000-00-00'), '-')
That is essentially just a shorter way of writing this:
SELECT CASE
WHEN yourdatecolumn IS NULL OR yourdatecolumn = '0000-00-00' THEN '-'
ELSE yourdatecolumn
END
SELECT ID, IF(GRADUATIONDATE IS NULL, '-', GRADUATIONDATE) FROM TABLE
or
SELECT ID, IFNULL(GRADUATIONDATE,'-') FROM TABLE
精彩评论