如何优化嵌套条件SQL Server查询2008R2

时间:2016-05-06 07:33:53

标签: sql sql-server-2008

if {condition1} = '0'
begin
    if  {condition2} = 'Yes'
        Begin
            Set @SQLQuery = @SQLQuery + ' AND  '
        end
    else 
        begin
            Set @SQLQuery = @SQLQuery + ' AND  '
        end
end

2 个答案:

答案 0 :(得分:0)

正如@Pranav在评论中所述,您可以执行以下操作:

if {condition1} = '0'
  Set @SQLQuery = @SQLQuery + ' AND ' +
                  CASE WHEN {condition2} = 'Yes' THEN <whatever cond2=Yes>
                       ELSE <whatever cond2<>Yes> END

答案 1 :(得分:0)

希望这有帮助,只需在运行此

之前为@SQLQuery分配任何或空值
SELECT @SQLQuery+ = CASE WHEN CONDITION1='0' AND CONDITION2='Yes' THEN
' AND '
WHEN CONDITION1='0' THEN
' AND '
END