Problem : An INSERT EXEC statement cannot be nested Error

Problem : An INSERT EXEC statement cannot be nested Error

I have a procedure giving me this error:
Server: Msg 8164, Level 16, State 1, Procedure sp_NewConfirmsFullWeek, Line 20
An INSERT EXEC statement cannot be nested.

Here is the proc:
Alter Procedure sp_NewConfirmsFullWeekTotal (@COBDate      datetime)
As
SET NOCOUNT ON
Create Table #NC(Counterparty varchar(20), Mon int, Tue Int, Wed Int, Thu Int, Fri Int)

Insert Into #NC
EXEC sp_NewConfirmsFullWeek @COBDate

Select ‘Total’ As Total, SUM(Mon) As Mon, SUM(Tue) As Tue, SUM(Wed) As Wed , SUM(Thu) As Thu, SUM(Fri) As Fri
From #NC

Drop Table #NC
SET NOCOUNT OFF

It calls this other procedure that is working fine:

ALTER  Procedure sp_NewConfirmsFullWeek (@COBDate      datetime)
As

SET NOCOUNT ON

Declare @TheDay datetime,
@DayCtr      int

Exec sp_GetMonday @COBDate, @Mon = @TheDay out

CREATE TABLE #NewConfirms(      COBDate       datetime,
NewConfirms       int,
Counterparty        varchar(20)
)

While datepart(dw, @TheDay)
BEGIN
–Print ‘Inserting ‘ + CONVERT(Varchar(20), @TheDay)
–PRINT ”
Insert Into #NewConfirms
Exec sp_NewConfirms @TheDay
SET @TheDay = @TheDay + 1
END

Select       Counterparty,
SUM(CASE WHEN datepart(dw, COBDate) = 2 THEN NewConfirms * 1 ELSE NewConfirms * 0 END) AS Mon,
SUM(CASE WHEN datepart(dw, COBDate) = 3 THEN NewConfirms * 1 ELSE NewConfirms * 0 END) AS Tue,
SUM(CASE WHEN datepart(dw, COBDate) = 4 THEN NewConfirms * 1 ELSE NewConfirms * 0 END) AS Wed,
SUM(CASE WHEN datepart(dw, COBDate) = 5 THEN NewConfirms * 1 ELSE NewConfirms * 0 END) AS Thu,
SUM(CASE WHEN datepart(dw, COBDate) = 6 THEN NewConfirms * 1 ELSE NewConfirms * 0 END) AS Fri
From       #NewConfirms
Group By CounterParty

Drop table #NewConfirms

SET NOCOUNT OFF

I don’t understand why I’m getting this error. The procedure it calls uses the same technique of populating a temp table with a procedure and that works fine.
Does anyone know what’s going on?


 

Solution: An INSERT EXEC statement cannot be nested Error

ptjcb : well, actually it’s a bit more subtle than that, what you say is true but kind of suggest one could solve it by adding an in-between procedure, which (as I’m sure you know), doesn’t work.

“You can use the “INSERT EXEC” statement to get the output of a SP into a table only ONCE for the entire stack”

(so even if you have like one SP calling another, and that one’s calling another SP, and that one is etc.. etc…   there can be only 1 (one!)  part (sp) that uses the this method)

My ‘best’ suggestion to get around this is by passing the output table to the called procedure(s) and have it (them) use dynamic sql to fill it (them) up, or simply hard-code it into the called procedure(s).
(=> passing the variable means dynamic sql, wich you might not like, hardcoding the table names makes it a lot less flexible. Depending ont he situation you may prefer one to the other)