Wednesday, September 15, 2010

An INSERT EXEC statement cannot be nested

I ran into the following problem: if a procedure is using INSERT EXEC, and you try to INSERT EXEC that procedure, you get the following error message:
An INSERT EXEC statement cannot be nested.

Example:

USE MyDB
GO

CREATE PROC dbo.Proc1
AS
SELECT 1
GO

CREATE PROC dbo.Proc2
AS
SET NOCOUNT ON
CREATE TABLE #t (value INT)
INSERT INTO #t
EXEC Proc1
SELECT * FROM #t
GO

CREATE TABLE #results (value INT)

INSERT INTO #results
EXEC dbo.Proc2

An INSERT EXEC statement cannot be nested.

I found the following simple workaround:

INSERT INTO #results
SELECT * FROM OPENROWSET('SQLNCLI', 'server=(local);trusted_connection=yes', 'EXEC MyDB.dbo.Proc2')