Reputation: 1409
I have a procedure:
ALTER PROCEDURE SP_CREATETABLE
(
@newTableName NVARCHAR(200)
)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = 'create table @tableName (id int identity(1,1) primary key )'
PRINT @sql
EXEC sp_executesql @sql, N'@tableName nvarchar(200)', @newTableName
END
When I try to execute this:
EXEC SP_CREATETABLE 'NEWTABLENAME';
I get this error:
Msg 102, Level 15, State 1, Line 12
Incorrect syntax near '@tableName'.
Upvotes: 2
Views: 440
Reputation: 1270513
The reason you cannot create the table is because parameters only work for values in the query, not for table names or column names.
I often approach this using REPLACE()
:
ALTER PROCEDURE SP_CREATETABLE (
@newTableName NVARCHAR(200)
)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = 'create table @tableName (id int identity(1,1) primary key )';
SELECT @sql = REPLACE(@sql, '@tableName', @newTableName);
PRINT @sql;
EXEC sp_executesql @sql;
END;
Upvotes: 1
Reputation: 950
You will need something like this:
ALTER PROCEDURE SP_CREATETABLE
(
@newTableName NVARCHAR(200)
)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = 'create table ' + QUOTENAME(@newTableName) + ' (id int identity(1,1) primary key )'
PRINT @sql
EXEC sp_executesql @sql
END
EXEC SP_CREATETABLE 'NEWTABLENAME';
Upvotes: 4