Create table dynamically while passing the table name

Harreni
Harreni used Ask the Experts™
on
Hi Experts,

I want to pass the table name dynamically to the following query and get it created:

DECLARE @SQL varchar(MAX);
	DECLARE @TableName varchar(255);

	SET @SQL = '"CREATE TABLE +  @TableName+ (
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[AgencyName] [nvarchar](255) NULL,
		[ServiceID] [nvarchar](255) NULL,
	
		) ON [PRIMARY]"';

execute (@SQL);

Open in new window


And usually, I got an error with the single quotation. So, could you please tell me what the correct way to get it working?

Thanks a lot in advance.
Harreni
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT Engineer
Distinguished Expert 2017
Commented:
Try this and see the difference:
SET @SQL = 'CREATE TABLE ' +  @TableName+ ' (
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[AgencyName] [nvarchar](255) NULL,
		[ServiceID] [nvarchar](255) NULL,
		) ON [PRIMARY]'

Open in new window

Author

Commented:
Thanks a lot Vitor, It works 100%

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial