如果传递参数则执行 CTE

Execute CTE if parameter is passed

我有一个包含一些 CTE 的存储过程。例如:

create or alter proc sp_test
    (@param1 int,
     @param2 int,
     @param3 int)
as
begin
    ;with cte_a as
    (
        select * 
        from table_a 
        where param1 = @param1
    ),
    cte_b as 
    (
        select * 
        from table_b 
        where param2 = @param2
    )
    ....

   //what I would like
   if @param3 > 0
   begin
       cte_c as 
       (select * from table_c)
   end
end

有没有一种方法可以定义一个仅在传递参数时才能与先前定义的 cte 一起使用的 cte?

PS:我知道我可以从参数检查开始,然后添加一个else语句,但是这个存储过程非常大,我认为这种方式会更简单(如果可能的话)。

对于您的用例,您可以使用临时 table 或 table 变量,因为 CTE 在后续 select 语句后立即失去范围。

Reference from MSDN

Common Table Expression
Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE or MERGE statement.

select * INTO #cte_a
from table_a 
where param1 = @param1

select * INTO #cte_b
from table_b 
where param2 = @param2
 
//what I would like
if @param3 > 0
begin
      select * INTO #cte_c from table_c 
end