SQL Date Return If Null Then Blank

16,335

In SQL Server:

Since you want to use an empty string instead of null, then you are going to be converting to a string. You can use the size of 10 along with style 120 to return iso format (without the time portion) like so:

select 
    dob = isnull(convert(varchar(10),BirthDateTime,120),'')
  , [Admission Date] = isnull(convert(varchar(10),ServiceDateTime,120),'')
  , [Discharge Date] = isnull(convert(varchar(10),DischargeDateTime,120),'')
from ...

You can find the other style codes for convert() here: docs: cast and convert

Share:
16,335

Related videos on Youtube

cmpmd2
Author by

cmpmd2

Updated on June 04, 2022

Comments

  • cmpmd2
    cmpmd2 almost 2 years

    I currently have the following code:

    CASE WHEN CONVERT(DATE, BirthDateTime) IS NULL THEN '' END AS DOB,
    CASE WHEN CONVERT(DATE, ServiceDateTime) IS NULL THEN '' END AS [Admission Date],
    CASE WHEN CONVERT(DATE, DischargeDateTime) IS NULL THEN '' END AS [Discharge Date],
    

    It returns:

    enter image description here

    What is the best way to still convert the date to Date (original field is datetime) and if it is Null then return blank or ' '

    Thanks in advance!

    • Ken White
      Ken White over 6 years
      What DBMS are you using? When you were writing your question and added the SQL tag, a large box was shown to you that suggested you also add a tag for the specific DBMS, because syntax and functionality differ between them. Why did you decide to ignore that suggestion?
    • Amit Kumar Singh
      Amit Kumar Singh over 6 years
      ISNULL (COLUMNNAME, '') in sql server, and check out coalesce as well for learning purpose .
    • cmpmd2
      cmpmd2 over 6 years
      What DBMS are you using? --- I don't understand. SQL Server 2012?
    • cmpmd2
      cmpmd2 over 6 years
      When you were writing your question and added the SQL tag, a large box was shown to you that suggested you also add a tag for the specific DBMS, because syntax and functionality differ between them. Why did you decide to ignore that suggestion? --- I have been tagging them. I don't know why it doesn't show.
    • Andomar
      Andomar over 6 years
      @cmpmd2: you have to click the tag after typing part of it, or type it in full
    • M3talM0nk3y
      M3talM0nk3y over 6 years
  • Andomar
    Andomar over 6 years
    That won't work, both arguments to isnull must have the same type
  • Zohar Peled
    Zohar Peled over 6 years
    I would change just one thing - use char(10) instead of varchar(10), since it's a fixed length.
  • SqlZim
    SqlZim over 6 years
    @ZoharPeled Usually I would, but since null is being converted to an empty string, and the conversion would change the empty string into 10 blank spaces... I just don't like a bunch of space characters in my result set instead of an empty string.