COALESCE将结果值加倍

时间:2018-08-19 06:31:16

标签: sql sql-server tsql coalesce

功能上

SELECT @ProcedureName = COALESCE(@ProcedureName + ',', '') + ProcedureName
FROM V_Procedures P 
inner join MedicalRecords MR on P.Medical_Record=MR.Medical_Record 
where ProcedureName IS NOT NULL and MR.Admission_No  = @Admission_No 
and Field = 18

得到许多以逗号分隔的双打,是否有可能避免?

例如结果值显示为

CONCHOTOMY,FESS-FUNCTIONAL ENDOSCOPIC (NASAL) SINUS SURGERY,CONCHOTOMY,FESS-FUNCTIONAL ENDOSCOPIC (NASAL) SINUS SURGERY,SUBMUCOUS RESECTION OF NASAL SEPTUM

2 个答案:

答案 0 :(得分:1)

您似乎想要distinct

SELECT DISTINCT @ProcedureName = COALESCE(@ProcedureName + ',', '') + ProcedureName
FROM V_Procedures P INNER JOIN 
     MedicalRecords MR 
     ON P.Medical_Record=MR.Medical_Record 
WHERE ProcedureName IS NOT NULL AND 
      MR.Admission_No  = @Admission_No AND 
      Field = 18;

答案 1 :(得分:0)

代替COALESCE,请尝试使用CONCAT。还有GROUP BY。

update test1 set start_date = sysdate + numToDSInterval(10 * (table_id - rownum), 'second')
where table_id >= 223 and table_id <= 228;

诀窍是,向其添加NULL时CONCAT不会返回NULL。但是DECLARE @ProcedureName VARCHAR(max); SELECT @ProcedureName = CONCAT(@ProcedureName + ',', ProcedureName) FROM V_Procedures P JOIN MedicalRecords MR ON P.Medical_Record = MR.Medical_Record WHERE ProcedureName IS NOT NULL AND MR.Admission_No = @Admission_No AND Field = 18 GROUP BY ProcedureName 确实如此。因此,因为@ProcedureName首先是NULL,所以结果将不会以逗号开头。