我有下面的代码可以工作,并且可以完成所需的工作。
但是,我需要通过IF语句来管理两个确切的查询。
有人能看到一种消除IF的方法吗?
IF @ReportClientTypeAbbreviation = 'IA'
BEGIN
select
*
from
Client CR
Inner Join LookUp.ClientType CT on
CR.ClientTypeID = CT.ClientTypeID
where
CR.SubmitDate >=@ReportStartDate and CR.SubmitDate <=@ReportEndDate and
CT.ReportClientTypeAbbreviation = 'IA'
END
ELSE
BEGIN
select
*
from
Client CR
Left Join LookUp.ClientType CT on
CR.ClientTypeID = CT.ClientTypeID
where
CR.SubmitDate >=@ReportStartDate and CR.SubmitDate <=@ReportEndDate and
(CT.ReportClientTypeAbbreviation = 'NonIA' or CT.ReportClientTypeAbbreviation is null)
END
答案 0 :(得分:4)
您可以使用AND / OR逻辑组合查询,这是SQL查询的基本知识。下面显示了如何执行此操作(未经测试-但应给您足够的操作空间):
select *
from Client CR
left join LookUp.ClientType CT on CR.ClientTypeID = CT.ClientTypeID
where CR.SubmitDate >= @ReportStartDate and CR.SubmitDate <= @ReportEndDate
and (
(CT.ReportClientTypeAbbreviation = 'IA' and @ReportClientTypeAbbreviation = 'IA')
or (
@ReportClientTypeAbbreviation != 'IA' and (CT.ReportClientTypeAbbreviation = 'NonIA' or CT.ReportClientTypeAbbreviation is null)
)
)