2

For some reasons, I am trying to create a dynamic script to drop tables that I created before. I couldnt do the syntax right and I need help for this matter.

When I run my script, it gives the error:

"Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'."

and this is my script. It has an error in sp_executesql statement, I guess. How can I fix this?

DECLARE @sql VARCHAR(MAX);
DECLARE @tmpTableName VARCHAR(max);
SET @tmpTableName = '##gmAAA_COLLATION';

SET @sql = 'DROP TABLE @tmpTableName';

EXEC sp_executesql @sql, N'@tmpTableName NVARCHAR(max)', @tmpTableName;
Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Arif YILMAZ
  • 5,754
  • 26
  • 104
  • 189

4 Answers4

3

You cannot do this with static SQL, i.e. a table name can never be a parameter in SQL statements like these. This is also true for column names, schema names etc.

If you want to do this using sp_executesql, you can build the SQL dynamically as follows:

SET @sql = 'DROP TABLE '+QUOTENAME(@tmpTableName);

EXEC sp_executesql @sql;

PS: The @stmt parameter of the sp_executesql procedure needs to be of type NVARCHAR(...).

TT.
  • 15,774
  • 6
  • 47
  • 88
2
SET @sql = 'DROP TABLE '+@tmpTableName;

EXEC sp_executesql @sql;
Chanukya
  • 5,833
  • 1
  • 22
  • 36
1

The sp_executesql requires nvarchar for the @stmt and @params parameters

so change the data Types of variables form varchar to be nvarchar as following

DECLARE @sql NVARCHAR(MAX);
DECLARE @tmpTableName VARCHAR(max);
ahmed abdelqader
  • 3,409
  • 17
  • 36
0

Try the following query:-

    SET @sql = 'DROP TABLE @tmpTableName'; EXEC (@sql)

OR

DECLARE @sql NVARCHAR(MAX);
DECLARE @tmpTableName NVARCHAR(max)
SET @tmpTableName = '##gmAAA_COLLATION';


SET @sql = 'DROP TABLE'+QUOTENAME(@tmpTableName);

EXEC sp_executesql @sql,N'@tmpTableName NVARCHAR(max)',@tmpTableName 
Chanukya
  • 5,833
  • 1
  • 22
  • 36
Mansoor
  • 4,061
  • 1
  • 17
  • 27