Replacing NULL and empty string within Select statement

前端 未结 4 781
栀梦
栀梦 2020-12-03 05:20

I have a column that can have either NULL or empty space (i.e. \'\') values. I would like to replace both of those values with a valid value like

相关标签:
4条回答
  • 2020-12-03 05:40

    Sounds like you want a view instead of altering actual table data.

    Coalesce(NullIf(rtrim(Address.Country),''),'United States')
    

    This will force your column to be null if it is actually an empty string (or blank string) and then the coalesce will have a null to work with.

    0 讨论(0)
  • 2020-12-03 05:49

    Try this

    COALESCE(NULLIF(Address.COUNTRY,''), 'United States')
    
    0 讨论(0)
  • 2020-12-03 05:51

    For an example data in your table such as combinations of

    '', null and as well as actual value than if you want to only actual value and replace to '' and null value by # symbol than execute this query

    SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
    

    and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull function but here only i am mentioning IIF function

    SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name  
    SELECT IIF(Column_Name  = '', '#', Column_Name) FROM Table_Name  
    -- and syntax of this query
    SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
    
    0 讨论(0)
  • 2020-12-03 06:06

    An alternative way can be this: - recommended as using just one expression -

    case when address.country <> '' then address.country
    else 'United States'
    end as country
    

    Note: Result of checking null by <> operator will return false.
    And as documented: NULLIF is equivalent to a searched CASE expression
    and COALESCE expression is a syntactic shortcut for the CASE expression.
    So, combination of those are using two time of case expression.

    0 讨论(0)
提交回复
热议问题