【问题标题】:SQL with clause in stored procedure存储过程中的 SQL with 子句
【发布时间】:2017-04-26 14:15:51
【问题描述】:

是否可以在存储过程中定义 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 语句之前收到“语法错误”错误

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

【问题讨论】:

  • 你最好描述一下整个场景。现在看起来很奇怪:你的 sp 可能会返回结果集,也可能不会。如何使用它?

标签: sql sql-server common-table-expression with-statement


【解决方案1】:

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

您的 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

【讨论】:

    【解决方案2】:

    只需使用临时表或表变量即可。 SQL Server 的作用域规则确保这样的表在过程结束时被删除:

    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;
    

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

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        猜你喜欢
        • 2018-12-14
        • 1970-01-01
        • 2014-01-24
        • 1970-01-01
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        • 1970-01-01
        相关资源
        最近更新 更多