I am using OBJECT_ID to check the existence of the temporary table inside the inner procedure to make sure that, we are not having nested insert execute scenario.
When we check that the table is not existing only, we create the table and insert into the table.
I have provided sample code below for your reference.
--Procedure for INSERT...EXEC
CREATE PROCEDURE ValuesGetForInsert
AS
BEGIN
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3;
END
GO
--Outer Insert Procedure
CREATE PROCEDURE dbo.OuterInsert
AS
BEGIN
IF OBJECT_ID('tempdb..#Table1') IS NULL
BEGIN
CREATE TABLE #Table1(a int);
INSERT INTO #Table1(a)
EXECUTE ValuesGetForInsert;
END
EXECUTE InnerInsert;
SELECT 'OuterInsert',* FROM #Table1;
END
GO
--Inner Insert Procedure
CREATE PROCEDURE dbo.InnerInsert
AS
BEGIN
IF OBJECT_ID('tempdb..#Table1') IS NULL
BEGIN
CREATE TABLE #Table1(a int);
INSERT INTO #Table1(a)
EXECUTE ValuesGetForInsert;
END
SELECT 'Inner Insert', * FROM #Table1
END
GO
--Executing outer insert or inner insert indepenently
EXECUTE dbo.OuterInsert;
EXECUTE dbo.InnerInsert;
GO