0

I've been looking for a while but still can not find the answer. I am trying to use a very simple stored procedure sp_executesql to create a database or a table.

    exec sp_executesql
     N'create database @d',
     N'@d nvarchar(1)',
     @d = 'a';

or this

    exec sp_executesql 
    N'create table @d',
    N'@d nvarchar(9)',
    @d=N'MyTable'

keep getting this message:

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '@d'.

I dont understand why?

Yinon Dotan
  • 137
  • 1
  • 12
  • 1
    Possible duplicate of [How to use a variable for the database name in T-SQL?](https://stackoverflow.com/questions/727788/how-to-use-a-variable-for-the-database-name-in-t-sql) You should know that what is not possible when executed as literal text in non-dynamic SQL is also not possible when executed as literal text via dynamic SQL. So you can't just use variables to refer to objects. But, since you're using dynamic SQL, you *can* concatenate them into the query so they're not variables anymore. – underscore_d Jan 10 '18 at 12:42
  • I had no clue you could not use a database as a parameter. That is why I did not find the above answer, my question came up as a result of studying ado.net. – Yinon Dotan Jan 10 '18 at 13:23

1 Answers1

1

SQL Server will not accept a variable in this case. See here for options:

How to use a variable for the database name in T-SQL?

Soukai
  • 463
  • 5
  • 8