Reliably dropping a SQL Server database if it exists
I often need to write scripts that drop and recreate databases. The hard part of that has always been reliably dropping a database if it already exists. And no, you wouldn’t think that would be hard, but it is.
Built in Command
T-SQL has a built-in command for this.
DROP DATABASE IF EXISTS Sales;
You’d hope that would work, but it doesn’t. I wish it did. The problem is that it will fail if anyone is connected to the DB. And to check if anyone is attached, you first need to check if the DB exists, so it makes the whole “IF EXISTS” part that was added to this command, completely pointless.
2021-06-24