在sql中使用循环创建多个表

时间:2017-04-21 04:22:47

标签: sql-server

我想创建具有相同列名的多个表。表的名称是table1,table2,table3等。有人可以帮我纠正代码行4中的'table @ cnt'部分吗?

declare @cnt int = 0;
while @cnt < 7
begin 

CREATE TABLE table@cnt(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)   
);

set @cnt = @cnt + 1;
end;

3 个答案:

答案 0 :(得分:1)

declare @cnt int = 0;
while @cnt < 7
begin 

declare @q nvarchar(max) = 'CREATE TABLE table' + convert(varchar(10), @cnt) + '(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)   
);'

exec (@q)

set @cnt = @cnt + 1;
end;

答案 1 :(得分:0)

您可以像这样使用动态查询

DECLARE @cnt int = 1
DECLARE @TableName varchar(20) = CAST(@cnt as varchar(20))

DECLARE @query nvarchar(max) = 
                   N'CREATE TABLE '+  @TableName + 
                   ' (
                   PersonID int,
                   LastName varchar(255),
                   FirstName varchar(255),
                   Address varchar(255),
                   City varchar(255)   
                   )'
EXEC (@query)

答案 2 :(得分:0)

DECLARE @cnt int = 1
While(@cnt <=10)
Begin
DECLARE @query nvarchar(max) = 
                   N'CREATE TABLE '+'table_'+CASt(@cnt  AS VARCHAR(10))+
                   ' (
                   PersonID int,
                   LastName varchar(255),
                   FirstName varchar(255),
                   Address varchar(255),
                   City varchar(255)   
                   )'

EXEC (@query)
SET @cnt=@cnt+1
END