How to Substitute a String if record is NULL in T-SQL

后端 未结 3 1691
温柔的废话
温柔的废话 2020-12-11 16:13

I\'m writing a T-SQL report that shows the number of accounts that are in different statuses for different customers. The report results in something like:

C         


        
相关标签:
3条回答
  • 2020-12-11 16:47

    You can use COALESCE or ISNULL. The former is standard and returns the first NOT NULL argument (or NULL if all arguments are NULL)

    SELECT COALESCE(micv.value,'Pending') as value
    

    ISNULL is restricted to only 2 arguments but is more efficient in SQL Server if the first value to be tested is expensive to evaluate (e.g. a subquery).

    One potential "gotcha" with ISNULL to be aware of is that it returns the datatype of the first parameter so if the string to be substituted is longer than the column datatype would allow you will need a cast.

    E.g.

    CREATE TABLE T(C VARCHAR(3) NULL);
    
    INSERT T VALUES (NULL);
    
    SELECT ISNULL(C,'Unknown')
    FROM T
    

    Would return Unk

    But ISNULL(CAST(C as VARCHAR(7)),'Unknown') or COALESCE would both work as desired.

    0 讨论(0)
  • 2020-12-11 16:58

    you can also use ISNULL('value', 'replacewithvalue')

    0 讨论(0)
  • 2020-12-11 16:59
    SELECT
       sr.sales_region_name   AS SalesRegion
       , ISNULL(micv.value,'Pending')
       , COUNT(sr.sales_region_name)
    FROM prospect p
    --(...)
    

    Go check ISNULL for further info.

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