在where

时间:2016-10-25 07:32:23

标签: sql sql-server-2008 where-clause

我想添加条件'其中'条款取决于' 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 

但这种方法效果不错,有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点,一种是使用动态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 ')

答案 1 :(得分:0)

你需要使用动态SQL,但为什么不只是有两个执行SQL的语句,所以而不是set @strSQLClause = 'AND ...',只需要一个带有你需要的条件的select语句

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 
            INNER JOIN HOSeleMonthsOccupied sm 
                ON sr.MonthsOccupied=sm.MonthsOccupiedCd
    WHERE   AppId=@AppId;

    IF(CONVERT(INT,LTRIM(RTRIM(@strMonthsOccupied))) > 9)
    BEGIN
        SELECT  * 
        FROM    SHSeleQuestions 
        WHERE   MasterCompanyId='09' 
        AND     QuestionCd!='Q8';
        RETURN;
    END
END

SELECT  * 
FROM    SHSeleQuestions 
WHERE   MasterCompanyId='09';

话虽如此,上面有很多问题,我真的不知道从哪里开始。您声明您的变量,然后为其分配一个不确定的值:

DECLARE @strMonthsOccupied CHAR(1)

SELECT  DISTINCT @strMonthsOccupied = sm.MonthsOccupiedDesc 
FROM    HOStructureRating sr 
        INNER JOIN HOSeleMonthsOccupied sm 
            ON sr.MonthsOccupied=sm.MonthsOccupiedCd
WHERE   AppId=@AppId;

如果查询返回多行,则没有明确的逻辑来指定应该赋值变量的值。 nex问题是,此CHAR(1)变量显然是基于您尝试转换的数字:

IF(CONVERT(INT,LTRIM(RTRIM(@strMonthsOccupied))) > 9)

为什么不切断中间人并宣布INT开始。下一点是它是CHAR(1)因此实际上不足以存储大于9的任何内容,因此您的上述条件永远不会为真。

即使sm.MonthsOccupiedDesc10,变量也只会被截断为1,小于9,因此不符合条件,例如

DECLARE @strMonthsOccupied CHAR(1) = '10';
IF(CONVERT(INT,LTRIM(RTRIM(@strMonthsOccupied))) > 9)
    PRINT 'TRUE';
ELSE
    PRINT 'FALSE';