BACKGROUND
I have a procedure that has INSERT INTO ... EXEC (@sql)
from dynamic SQL.
This procedure's results is INSERTed INTO
table outside of procedure. When I attempt this, I get get an error:
[S0001][8164] An INSERT EXEC statement cannot be nested.
This error is discussed in other questions, but for inner procedures' calls instead of dynamic SQL:
- Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?
- An insert exec statement cannot be nested
Example with error:
-- =================================
-- table with test data
-- =================================
CREATE TABLE dbo.TestInsertIntoDynamicData1
(
data nvarchar(max)
)
INSERT INTO dbo.TestInsertIntoDynamicData1
VALUES ('one1'), ('two1'), ('three1')
GO
-- =================================
-- another table with test data
-- =================================
CREATE TABLE dbo.TestInsertIntoDynamicData2
(
data nvarchar(max)
)
INSERT INTO dbo.TestInsertIntoDynamicData2
VALUES ('one2'), ('two2'), ('three2')
GO
-- =================================
-- procedure with dynamic query
-- =================================
CREATE PROCEDURE dbo.TestInsertIntoDynamicProc
@TableName nvarchar(100)
AS
BEGIN
DECLARE @Results table(
data nvarchar(max)
)
DECLARE @sql nvarchar(max)
SET @sql = '
SELECT data
FROM dbo.' + @TableName + ';
'
-- FIRST INSERT INTO ... EXEC ...
INSERT INTO @Results -- this INSERT is required for example
EXEC (@sql)
SELECT *
FROM @Results;
END
GO
-- =================================
-- CALL
-- =================================
DECLARE @ResultsOfProc table(
data nvarchar(max)
)
-- SECOND INSERT INTO ... EXEC ...
INSERT INTO @ResultsOfProc (data)
EXEC dbo.TestInsertIntoDynamicProc @TableName = 'TestInsertIntoDynamicData2'
SELECT *
FROM @ResultsOfProc;
GO
DROP TABLE dbo.TestInsertIntoDynamicData1
DROP TABLE dbo.TestInsertIntoDynamicData2
DROP PROCEDURE dbo.TestInsertIntoDynamicProc
https://stackoverflow.com/a/2917775/7573844
QUESTION
How can we get around this error?