Concatenate table name loop sql server

4

I'm trying to populate a table of my with a loop in sql server follow the code:

declare @i int
set @i =1
while @i < 5
begin
INSERT INTO TABELA VALUES('teste')
set @i =  @i + 1
end

I would like to concatenate the name of the table in the insert with the number of the variable @i

Creating table1, table2, table3 ... etc

    
asked by anonymous 04.07.2014 / 16:40

2 answers

4

You can run any dynamic query in SQL Server using the routine sp_executesql .

Example:

declare @i int
declare @sql nvarchar(500)
set @i =1
while @i <= 5
begin

    set @sql = N'INSERT INTO TABELA' 
      + CONVERT(VARCHAR, @i) 
      + ' VALUES(''teste ' 
      + CONVERT(VARCHAR, @i) + ''')'
    execute sp_executesql @sql
    set @i =  @i + 1

end

Demo in SQLFiddle

    
04.07.2014 / 16:56
1
declare @i int
set @i =1
while @i < 5
begin
INSERT INTO TABELA VALUES('tabela' + CAST(@i AS VARCHAR))
set @i =  @i + 1
end
    
04.07.2014 / 16:55