如何在sql的case语句中将变量作为null传递

时间:2012-12-27 07:34:21

标签: sql-server sql-server-2008 sql-server-express

如何在此查询中传递“@abo为null”和“@rh为null”....这给出了错误...我正在这样做

select Distinct m.donorId,m.customid, FirstName + ' ' + Isnull(MiddleName,' ') + ' ' + isNull(LastName,'') as donorName  from m_donor as m inner join phlebotomyDetail as phy on m.DonorID=phy.DonorID left outer join  AVIRaw as avi ON  @prefix + RIGHT('000000' + CAST(m.DonorID AS VARCHAR(6)), 6) = avi.sampleid
            Where (m.donorId = @donorid OR @donorid is null) and
            (m.DOB =  @todate OR @todate Is Null) and
            (m.FirstName Like + '%' + @fullname + '%' OR m.MiddleName Like + '%' + @fullname + '%' OR m.LastName Like  +'%' + @fullname + '%' OR @fullname Is Null) and
            (m.cellPhone Like +'%' + @phone + '%' OR m.HomePhone Like + '%' + @phone + '%' OR m.WorkPhone Like + '%' + @phone + '%' OR m.OtherPhone Like + '%' + @phone + '%' OR  @phone Is Null) and
            (m.CustomID Like '%' + @custid OR @custid Is Null) AND
            (phy.BagNumber=@bagno OR @bagno is NULL) AND
            (phy.SegmentNo=@segno OR @segno is NULL ) AND
        (avi.result= CASE WHEN avi.AnalysisName = 'ABO' THEN @abo or @abo is null ELSE CASE WHEN avi.AnalysisName = 'RH' THEN left(@rh,3) or @abo is null END END)

1 个答案:

答案 0 :(得分:0)

我会尝试类似的事情:

avi.result= 
CASE WHEN avi.AnalysisName = 'ABO' 
THEN @abo 
ELSE 
    CASE WHEN avi.AnalysisName = 'RH' 
    THEN left(@rh,3) 
    END 
END

案例的结果必须与avi.result的类型兼容。

imho,你应该把ELSE放在第二个/内部的情况下,或者使用语法:

avi.result= 
CASE avi.AnalysisName 
    WHEN 'ABO' THEN @abo  
    WHEN 'RH' THEN left(@rh,3)  
    ELSE 'DEF' 
END