From BOL:
Local temporary tables are visible only in the current session ...... Temporary tables automatically when they go out of scope, unless explicitly deleted using DROP Table
The difference between your first and second procedures is that in the first case, the table is defined in the same area in which it is selected; in the second, EXEC () creates a table in its own scope, so the selection is not suitable in this case ...
However, note that the following works just fine:
CREATE PROCEDURE [dbo].[testProc3] AS SELECT * INTO
And this works because the EXEC scope is a child of the stored procedure scope. When a table is created in the parent area, it also exists for any of the children.
To give you a good solution, we will need to find out more about the problem you are trying to solve ... but if you just need to select from the created table, making a selection in the area of ββchild objects works fine:
CREATE PROCEDURE [dbo].[testProc4] AS EXEC('SELECT * INTO #temp FROM information_schema.tables; SELECT * FROM #temp') GO
source share