I have a question concerning a dynamic creation of temporary tables.
I need a while loop in which temporary tables are created in every cycle differing in their name using the variable @i
. So I specified the variables @CreateTableVerbGES
and @ShowTableVerbGES
with the code as strings and want to execute them in the loop.
Here is my code:
DECLARE @i int = 1
DECLARE @CreateTableVerbGES nvarchar(max)
DECLARE @ShowTableVerbGES nvarchar (max)
WHILE @i<4
BEGIN
SET @CreateTableVerbGES = 'CREATE TABLE #UnterBaugruppe'+CAST((@i) as nvarchar(max))+' ([IDTBG] [int] identity(1,1),[IDGES] [int] NULL,[Baugruppe1] [nvarchar](max) NULL,[IDBG1] [int] NULL,[Bauteil1] [int] NULL,[Baugruppe2] [nvarchar](max) NULL,[IDBG2] [int] NULL,[Bauteil2] [int] NULL,[Baugruppe3] [nvarchar](max) NULL,[IDBG3] [int] NULL,[Bauteil3] [int] NULL)'
SET @ShowTableVerbGES = 'SELECT * FROM #UnterBaugruppe'+CAST((@i) as nvarchar(max))
EXEC (@CreateTableVerbGES)
EXEC (@ShowTableVerbGES)
SET @i += 1
END
The problem is that it seems like the first cycle of the loop is running, because the first table #UnterBaugruppe1
is shown. But for the next two cycles there is a warning that the tables #UnterBaugruppe2
and #UnterBaugruppe3
are invalid and don't exist.
Does anybody have an idea why it isn't working?
I really need the tables in a loop because I want to insert different information in the loop as well dependent on @i
.