CTE 之后的 IF 语句

IF Statements After CTE's

今天我遇到了这个与 IF 语句有关的奇怪问题。完成 replacing/creating CTE 后,我在 CTE 之后有 IF 语句,并不断收到以下错误:

Incorrect Syntax near '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 以前是临时表。

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

谢谢。

你可以这样做:

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')
              )
         )
      )