2

I would like to create multiple tables with same column names. The name of the tables would be table1, table2, table3, etc. Can someone help me correct the part 'table@cnt' in codeline 4?.

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;
5
  • use dynamic sql with exec() i.e. 'CREATE TABLE table' + convert(varchar(10), @cnt) + '( PersonID int,' Commented Apr 21, 2017 at 4:25
  • @artm thank you for your prompt help. can you please elaborate more? Commented Apr 21, 2017 at 4:37
  • my problem still not solved. please help. Commented Apr 21, 2017 at 4:54
  • As artm mentioned, you'd replace CREATE TABLE table@cnt(PersonID int...); with EXEC('CREATE TABLE table' + convert(varchar(10), @cnt) + '(PersonID int...);'); Commented Apr 21, 2017 at 4:57
  • @Sonam Please try to search .... You had keyword dynamic sql from @artm Commented Apr 21, 2017 at 4:59

3 Answers 3

3
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;
Sign up to request clarification or add additional context in comments.

1 Comment

it worked like a magic. thanks a lot for your help. have a good day.
0

You could use dynamic query like this

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)

3 Comments

The above throws error Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'table'.
But it will creates only One table it deosn't loop over as tab1 ,tab2 ...
You could use it with WHILE ... in OP's post.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.