Lif*_*ona 0 t-sql sql-server 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')
)
Run Code Online (Sandbox Code Playgroud)
另外要包括的是,这样做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;
Run Code Online (Sandbox Code Playgroud)
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')
);
Run Code Online (Sandbox Code Playgroud)
您也可以将这些条件添加到单个查询中,但是我认为这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')
)
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |