CTE之后的IF声明

时间:2019-07-08 14:23:17

标签: sql-server tsql common-table-expression

今天,我遇到了与IF语句有关的怪异问题。完成替换/创建CTE之后,在CTE之后有IF语句,并不断出现以下错误:

  

'if'附近的语法不正确

查询:

-- Other CTE's above.
CTE6 AS 
(
    SELECT
        -- Multiple Columns
    FROM
        table1
)
-- When the Query runs, I'd like it to use the correct IF BLOCK.

-- Error starts here.
if @param_policy = '1' 
    select * from CTE4
    where mid not in (select distinct mid from CTE6)
        and [CN] = @param_policy

if @param_policy = '2' 
    select * from CTE4 
    where mid not in (select distinct mid from CTE6)
        and [CN] = @param_policy

if @param_policy = '3' 
    select * from CTE4 
    where mid not in (select distinct mid from CTE6)
        and [CN] = @param_policy                

if @param_policy = '4' 
    select * from CTE4 
    where mid not in (select distinct mid from CTE6)
        and [CN] = @param_policy   
-- UPDATED

select * from CTE4 WHERE @param_policy = 'batch' and mid not in (select distinct mid from CTE6)

and not
(([Client Number] ='5' and  Pnum = 'IN' )
or ([Client Number] ='6' and  Pnum = 'G')
or [Client Number] in ('7' , '8', '9')
)


还包括在内,当它执行select * from CTE4时,它认为CTE4是无效的,而且,它也没有将“ mid”识别为有效列。

我的CTE以前是临时表。

有人知道如何解决这个问题吗?

谢谢。

1 个答案:

答案 0 :(得分:6)

您可以执行以下操作:

select *
from CTE4
where @param_policy in ('1', '2', '3', '4')  and
      mid not in (select distinct mid from CTE6) and
      [CN] = @param_policy;

IF是T-SQL代码的控制流。它不是SELECT查询语法的一部分。

更一般地,您可以使用union all做您想做的事情:

select *
from CTE4
where @param_policy in ('1', '2', '3', '4')  and
      mid not in (select distinct mid from CTE6) and
      [CN] = @param_policy
union all
select *
from CTE4 
where @param_policy = 'batch' and
      mid not in (select distinct mid from CTE6) and
      not (([Client Number] ='5' and  Pnum = 'IN' ) or
           ([Client Number] ='6' and  Pnum = 'G') or
           ([Client Number] in ('7' , '8', '9')
          );

您也可以将这些条件添加到单个查询中,但是我认为union all是您正在寻找的更通用的方法。

编辑:

或者,仅在WHERE中使用更复杂的逻辑:

select *
from CTE4
where mid not in (select distinct mid from CTE6) and
      ( (@param_policy in ('1', '2', '3', '4')  and
         [CN] = @param_policy
         ) or
         (@param_policy = 'batch' and
          not (([Client Number] ='5' and  Pnum = 'IN' ) or
               ([Client Number] ='6' and  Pnum = 'G') or
               ([Client Number] in ('7' , '8', '9')
              )
         )
      )