SQL with 存储过程中的子句

SQL with clause in stored procedure

是否可以在存储过程中定义一个 with 子句并在 if else 语句中使用它,因为我总是出错?

BEGIN
    WITH Test (F, A) AS
    (
        SELECT FM.ID, FM.Name 
        FROM [Test.Abc] FM
        INNER JOIN [Organization] O on O.ABCID = FM.ID
    )

    IF(@var = 'case1')
    BEGIN
        SELECT * 
        FROM Test F
        WHERE NOT F.ID = 'someID'
    END

我总是在 if 语句

之前收到 "Incorrect syntax" 错误

如果我将 with 子句移动到 if 语句中,它就可以正常工作。但是我需要外面的 with 语句才能在不同的 if else 语句中重用它。

只需使用临时 table 或 table 变量。 SQL 服务器的作用域规则确保这样的 table 在过程结束时被删除:

BEGIN
    select FM.ID, FM.Name
    into #test
    from [Test.Abc] FM inner join
         [Organization] O
         on O.ABCID = FM.ID;

    IF(@var = 'case1')
        BEGIN
            select *
            from #Test F
            where not F.ID = 'someID'
        END;

这样做的好处是您可以向 table 添加索引,这可能会提高性能。

WITH 不是独立的,它始终是整个语句的一部分,并且只是一个语句。
在其声明范围之外无法识别它。

BEGIN

    with my_cte (n) as (select 1+1)
    select * from my_cte

    -- The following statement yields the error "Invalid object name 'my_cte'."    
    -- select * from my_cte

END

这是您得到的相同答案的另一个版本:

您的 with common table expresson 必须与调用它的查询位于同一语句中,并且必须由查询(或其他 cte)或它引用是语法错误。

参考创建和使用Common Table Expressions的文档指南。

BEGIN -- doing stuff
-- .... doing stuff over here
IF(@var = 'case1')
    BEGIN
        with Test (F, A) as (
        select FM.ID, FM.Name from [Test.Abc] FM
        inner join [Organization] O on O.ABCID = FM.ID
          )     
        select * from Test F
        where not F.ID = 'someID'
    END
-- .... and doing some other stuff over here too
END -- done with this stuff