【问题标题】:Can I use a stored procedure inside a with Statement in SQL Server?我可以在 SQL Server 的 with 语句中使用存储过程吗?
【发布时间】:2022-10-04 22:46:20
【问题描述】:

在 SQL Server 中,我可以使用 with 语句来简化如下查询:

with x as (select 1 as a)
select * from x

但是如果我想要使用的查询实际上是一个存储过程呢?

with x as (exec p_queryComplexSP 12345, 0, null,'D+0','D+1095','Hour','GMT', 1)
select * from x
-- fails: SQL Error [156] [S0001]: Incorrect syntax near the keyword 'exec'.

有没有正确的方式来表达这个查询?

【问题讨论】:

    标签: sql-server stored-procedures


    【解决方案1】:

    您不能在 CTE 中执行此操作,但可以使用临时表或表变量。

    DECLARE @ProcTable TABLE (Col1 INT, Col2 INT, Col3 INT);
    INSERT @ProcTable (Col1, Col2, Col3)
    EXEC p_MyProc;
    
    WITH x AS (SELECT Col1, Col2, Col3 FROM @ProcTable)
    SELECT *
    FROM x;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多