这是我的查询,它运行良好,但是当有一个空值的行时,填充函数不符合我的要求。任何替代方法吗? (例如:对于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
答案 0 :(得分:2)
您可以使用COALESCE
将NULL
值替换为默认值,即'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