【问题标题】:How to Substitute a String if record is NULL in T-SQL如果 T-SQL 中的记录为 NULL,如何替换字符串
【发布时间】:2015-04-12 16:57:34
【问题描述】:

我正在编写一个 T-SQL 报告,显示不同客户处于不同状态的帐户数量。报告结果如下:

Customer1    NoService        7
Customer1    IncompleteOrder  13
Customer1    NULL             9
Customer2    NoService        12
Customer2    Available        19
Customer2    NULL             3
...

“NULL”状态是有效数据,但我不想显示 NULL,而是显示“Pending”。到目前为止,这是我的 SQL:

USE cdwCSP;
SELECT
   sr.sales_region_name   AS SalesRegion
   , micv.value
   , COUNT(sr.sales_region_name)
FROM prospect p
   LEFT JOIN sales_region sr
     ON p.salesRegionId = sr.sales_region_number
   LEFT JOIN prospectOrder po
     ON po.prospectId = p.prospectId
   LEFT JOIN wo
     ON wo.prospectId = p.prospectId
   LEFT JOIN woTray wot
     ON wot.woId = wo.woId
   LEFT JOIN miscInformationCustomerCategory micc
     ON micc.prospectId = p.prospectId
   LEFT JOIN miscInformationCustomerValues micv
     ON micv.miscInformationCustomerCategoryId = micc.miscInformationCustomerCategoryId
   LEFT JOIN miscInformationCategory mic
     ON micc.miscInformationCategoryId = mic.miscInformationCategoryId
WHERE wot.dateOut IS NULL
     AND mic.categoryName LIKE '%Serviceability%'
GROUP BY sr.sales_region_name, micv.value
ORDER BY sr.sales_region_name, micv.value;

任何帮助将不胜感激,我仍在学习 T-SQL,所以这可能是一个容易回答的问题。

【问题讨论】:

    标签: sql sql-server string tsql null


    【解决方案1】:

    您可以使用COALESCEISNULL。前者是标准的,返回第一个 NOT NULL 参数(如果所有参数都是 NULL,则返回 NULL

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

    ISNULL 仅限于 2 个参数,但如果要测试的第一个值的评估成本很高(例如子查询),则在 SQL Server 中效率更高。

    需要注意ISNULL 的一个潜在“陷阱”是它返回第一个参数的数据类型,因此如果要替换的字符串长于列数据类型允许的长度,则需要进行强制转换。

    例如

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

    将返回Unk

    但是ISNULL(CAST(C as VARCHAR(7)),'Unknown')COALESCE 都可以正常工作。

    【讨论】:

    • 完美,这很好用而且看起来很有效。感谢您的帮助。
    【解决方案2】:

    你也可以使用ISNULL('value', 'replacewithvalue')

    【讨论】:

      【解决方案3】:
      SELECT
         sr.sales_region_name   AS SalesRegion
         , ISNULL(micv.value,'Pending')
         , COUNT(sr.sales_region_name)
      FROM prospect p
      --(...)
      

      前往ISNULL 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2016-10-10
        • 2021-04-04
        • 2020-06-18
        • 1970-01-01
        • 2011-05-20
        • 1970-01-01
        • 2019-04-16
        • 2017-05-12
        • 2012-03-26
        相关资源
        最近更新 更多