我想在“ where”子句中添加条件取决于“ if”条件,如下所示
Declare @strSQLClause varchar(50)
If (@QMasterCompanyId='09' and @State='FL' and (@LOB='HO' or @LOB='HP'))
Begin
Declare @strMonthsOccupied char(1)
select Distinct @strMonthsOccupied=sm.MonthsOccupiedDesc from HOStructureRating sr
join HOSeleMonthsOccupied sm on sr.MonthsOccupied=sm.MonthsOccupiedCd
where AppId=@AppId
If(CONVERT(int,LTRIM(RTrim(@strMonthsOccupied))) > 9)
Begin
set @strSQLClause ='AND QuestionCd!=Q8'
End
Else
set @strSQLClause =''
End
这样在我的查询中
select * from SHSeleQuestions where MasterCompanyId='09' + @strSQLClause
但是这种方法不能很好地工作,任何人都可以在这方面帮助我。
有两种方法可以做到这一点,一种是使用动态sql,另一种是下面提到的方法:
select *
from SHSeleQuestions
where MasterCompanyId='09' AND
1 = CASE WHEN LEN(@strSQLClause) > 0 AND QuestionCd != 'Q8' THEN 1
WHEN LEN(@strSQLClause) = 0 THEN 1 END
使用动态SQL
EXEC('select * from SHSeleQuestions where MasterCompanyId=''09''' + @strSQLClause ')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句