INSERT EXEC Statement cannot be nested [duplicate]

2019-07-19 15:10发布

问题:

This question already has an answer here:

  • Errors: “INSERT EXEC statement cannot be nested.” and “Cannot use the ROLLBACK statement within an INSERT-EXEC statement.” How to solve this? 10 answers

I have three Procedures MainProcedure,Procedure1,Procedure2

1) In Procedure1 I just have a select statement ,

2) In Procedure2 am calling the Procedure1 and inserting the Output to a #table

3) In the main Procedure I am calling the Procedure2 and iam trying to insert the Output to a #table which throws an error

Msg 8164, Level 16, State 1, Procedure Procedure2, Line 10 An INSERT EXEC statement cannot be nested.

I can resolve this using Openrowset where I need to use specify Server Name ,is there any other way to solve this by not specifying the servername details

please find the sample procedure for reference

    Create Proc Procedure1
    As
    Begin
    Select 'Arun' Name, 'Pollachi' Place
    Union
    Select 'Vedaraj' Name, 'Devakottai' Place
    End
    Go



    Create Proc Procedure2
    As
    Begin
    Create Table #Table1
    (
    Name Varchar(50), Place Varchar(50)
    )
    INSERT #Table1
    Exec Procedure1
    SELECT 'Procedure2' [Source], * FROM #Table1

    DROP TABLE #Table1
    End
    Go


    Create Proc MainProcedure
    As
    Begin
    Create Table #Table1
    (
    [Source] Varchar(50), Name Varchar(50), Place Varchar(50)
    )

    INSERT #Table1
    Exec Procedure2

    select * from #Table1

    DROP TABLE #Table1
    End
    Go

can any one change my main procedure and make it to get executed Thanks!!

回答1:

Like you said, openrowset will work, but other than that the only ways I can think of would be:

  1. Change both proc 1 and proc 2 to table based functions
  2. Change proc 2 to a CLR and put all logic in there
  3. Pass the tables around as table valued parameters

There's more info about the reasoning for this here:

https://connect.microsoft.com/SQLServer/feedback/details/294571/improve-insert-exec http://dataeducation.com/revisiting-isnull-coalesce-and-the-perils-of-micro-optimization/