Concatenate sql server loop table name

I'm trying to populate a table of mine 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 variable number @i

Creating table1, table2, table3 ...etc

Author: Rod, 2014-07-04

2 answers

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 no SQLFiddle

 4
Author: utluiz, 2014-07-04 15:01:48
declare @i int
set @i =1
while @i < 5
begin
INSERT INTO TABELA VALUES('tabela' + CAST(@i AS VARCHAR))
set @i =  @i + 1
end
 1
Author: Leonel Sanches da Silva, 2014-07-04 14:55:08