关键字 'IF' 附近的语法不正确,WITH 之后的 IF

Moh*_*Ali 1 t-sql stored-procedures if-statement syntax-error

我试图IF在 a 之后创建一个WITH,但它给了我错误Incorrect syntax near the keyword 'IF'

下面是我正在编写的存储过程的示例

CREATE PROCEDURE [dbo].[Proc_MyProc]
@MODE INT = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

WITH ss as (
    select col1, col2, col3, col4, col5
    from TableTest
)

IF @MODE = 1
    select col1 as A, col2, sum(col5) as col5sum
    from ss
    group by col1, col2
    order by col5sum desc
ELSE IF @MODE = 2
    select col1, col2, sum(col5) as col5sum
    from ss
    group by col1, col2, col3
    order by col5sum desc
ELSE IF @MODE = 3
    select col1, col2, sum(col5) as col5sum
    from ss
    group by col1, col2, col4
    order by col5sum desc

END

GO
Run Code Online (Sandbox Code Playgroud)

我尝试删除WITH和语法错误消失,但当然这不是一个解决方案

谢谢 :)

Gor*_*off 5

WITH与 一起使用,SELECT因此您需要重复WITH或使用临时表。

但在这种情况下,WITH实际上没有任何价值——让我假设它被简化了。

第一种方法是:

if @MODE = 1
    with ss as (
          select col1, col2, col3, col4, col5
          from TableTest
         )
    select col1 as A, col2, sum(col5) as col3sum
    from #ss
    group by col1, col2
    having SnQuantity > 0
    order by availability desc;
. . . 
Run Code Online (Sandbox Code Playgroud)

第二种方法是:

select col1, col2, col3, col4, col5
into #ss
from TableTest;

if @MODE = 1
    select col1 as A, col2, sum(col5) as col3sum
    from #ss
    group by col1, col2
    having SnQuantity > 0
    order by availability desc;
. . . 
Run Code Online (Sandbox Code Playgroud)