【问题标题】:Executing multiple sub stored procedures in a master stored procedure在主存储过程中执行多个子存储过程
【发布时间】:2019-07-08 14:18:26
【问题描述】:

我在一个主存储过程中使用多个存储过程(返回类型表格结果中只有 1 行):

CREATE PROCEDURE [dbo].[MAster_sp]
    (@param INT) 
AS
BEGIN
    EXEC [dbo].[sp1] @param 
    EXEC [dbo].[sp2] @param
    .
    .
END

然后输出是这样的

sp1 输出:

Male_Emp_Count       Female_Emp_Count 
--------------      ---------------- 
1                    0     

Sp2 输出:

empId               empJoiningDate                            
-----------         --------------
17                  2019-07-10    

。 . .

我希望这些结果在单个数据集行中作为对我的 API 的响应。

当我尝试插入表变量时,出现错误

INSERT EXEC 语句不能嵌套

这个错误是什么以及如何处理这个错误?我尝试了谷歌,但没有相关文章或信息可以帮助我理解这个问题。

CREATE PROCEDURE [dbo].[MAster_sp]
    (@param INT) 
AS
BEGIN
    CREATE TABLE #tempMainTbl 
    (
          c1 INT NULL,
          c2 INT NULL,
          c3 INT NULL,
          c4 INT NULL,
          c5 INT NULL
    )

    INSERT INTO #tempMainTbl (c1, c2, c3)
        EXEC [dbo].[sp1] @param 

    EXEC [dbo].[sp2] @param
    .
    .

    SELECT * from #tempMainTbl 
END

错误:

消息 8164,级别 16,状态 1,过程 dbo.[sp1],第 33 行 [批处理开始第 8 行]
不能嵌套 INSERT EXEC 语句。

我现在得到的实际结果:

sp1 输出

Male_Emp_Count Female_Emp_Count 
-------------- ---------------- 
1              0                

Sp2 输出

empId       empJoiningDate                            
----------- --------------
17          2019-07-10   

预期结果:

Male_Emp_Count       Female_Emp_Count     empId      empJoiningDate                                
--------------       ----------------     -----      --------------
1                     0                    17         2019-07-10

所有存储过程在单行中输出。

【问题讨论】:

  • 正确标记 - 代码通常始终特定于数据库引擎。大概您正在使用 SQL Server。并努力 - 在互联网上搜索该特定错误消息会发现很多讨论。
  • @SMor 我标记正确仍然无法找出问题,我会检查您标记的问题以获得更好的参考,感谢 Smor 的宝贵评论 :)

标签: sql sql-server stored-procedures


【解决方案1】:

所以这个问题与一个带有 insert into 的存储过程被另一个执行 insert into 的存储过程调用有关。

真正的唯一解决方案是合并程序。

以下是您现在可能拥有的: MAster_sp:

INSERT INTO #tempMainTbl (c1,c2,c3)
EXEC [dbo].[sp1] @param 

sp1:

Insert into #someothertemptable
exec someotherprocedure @param

不幸的是,您在 SQL Server 中无法做到这一点。以下是原因和解决方法: https://www.sqlservercentral.com/forums/topic/how-to-resolve-an-insert-exec-statement-cannot-be-nested-errorproblem

这是另一个帖子中的类似问题: Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

【讨论】:

  • 谢谢,现在我可以更好地理解这个问题了。 (y)
猜你喜欢
  • 2010-09-15
  • 1970-01-01
  • 2010-09-15
  • 2019-08-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2013-03-26
相关资源
最近更新 更多