MS SQL - Drop database name using variable is not possible

By xngo on December 3, 2019

In MS SQL Server, you can't run the DROP DATABASE statement with a variable name like the following:

-- This statement will not work.
DROP DATABASE @dbname;

It will display the following error message.

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

Instead, use the following statement.

EXEC('DROP DATABASE ' + @dbname);

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.