sql server中的STUFF()函数用于行列中的空格

时间:2016-03-21 13:59:56

标签: sql sql-server

这是我的查询,它运行良好,但是当有一个空值的行时,填充函数不符合我的要求。任何替代方法吗? (例如:对于NUll值,电话号码看起来像是464-987-987)

 SELECT 
     smsFDGPatientOrder.ID,
    STUFF((SELECT ', ' + [smsFDGPatientOrderPhoneNumbers].Number 
               FROM [smsFDGPatientOrderPhoneNumbers] 
               WHERE [smsFDGPatientOrderPhoneNumbers].FDGPatientOrder = smsFDGPatientOrder.ID
              ORDER BY Number
               FOR XML PATH('')), 1, 1, '') [PatientPhno]
     FROM smsFDGPatientOrder
    GROUP BY smsFDGPatientOrder.ID

不适用的示例数据

 ID     Name    Number          FDGPatientOrder Type    Index
189950  Home    630-561-3777    170638          1       NULL
189951  Home                    170638          1       NULL

1 个答案:

答案 0 :(得分:2)

您可以使用COALESCENULL值替换为默认值,即'464-987-987'

SELECT smsFDGPatientOrder.ID,
       STUFF((SELECT ', ' + COALESCE(s.Number, '464-987-987') 
              FROM [smsFDGPatientOrderPhoneNumbers] AS s
              WHERE s.FDGPatientOrder = smsFDGPatientOrder.ID
              ORDER BY Number
              FOR XML PATH('')), 1, 1, '') [PatientPhno]
FROM smsFDGPatientOrder
GROUP BY smsFDGPatientOrder.ID

修改

如果问题是由smsFDGPatientOrderPhoneNumbers中不存在的匹配记录引起的,您可以使用:

SELECT smsFDGPatientOrder.ID,
       COALESCE(
          STUFF((SELECT ', ' + s.Number
               FROM [smsFDGPatientOrderPhoneNumbers] AS s
               WHERE s.FDGPatientOrder = smsFDGPatientOrder.ID
               ORDER BY Number
               FOR XML PATH('')), 1, 1, ''),
          '464-987-987')) [PatientPhno]
FROM smsFDGPatientOrder
GROUP BY smsFDGPatientOrder.ID

<强> EDIT2:

要处理空格或空字符串值,您可以使用:

SELECT smsFDGPatientOrder.ID,
       STUFF((SELECT ', ' + s.Number
               FROM [smsFDGPatientOrderPhoneNumbers] AS s
               WHERE s.FDGPatientOrder = smsFDGPatientOrder.ID AND
                     LTRIM(s.Number) <> ''
               ORDER BY Number
               FOR XML PATH('')), 1, 1, '') [PatientPhno]
FROM smsFDGPatientOrder
GROUP BY smsFDGPatientOrder.ID