Quickly creating a new SQL Server database with SQLCMD
Posted: (EET/GMT+2)
Today's post is a quick tip about how to use SQLCMD to quickly create a new SQL Server database from the command line.
Usually, I have SQL Server Management Studio (SSMS) open and connected, so creating a new database is just a few clicks. But if you have your hands on the keyboard and focus on the command prompt/terminal, you can run the following:
sqlcmd -S localhost -E -Q "CREATE DATABASE MyNewDatabase;"
If you are not sure if the database exists or not (and want the command to succeed), you can add a little IF statement at the beginning:
sqlcmd -S localhost -E -Q "IF DB_ID('MyNewDatabase') IS NULL CREATE DATABASE MyNewDatabase;"
Note that if your server uses self-signed certificates, you can add the -C parameter to trust the certificate:
sqlcmd -S localhost -E -C -Q "IF DB_ID('MyNewDatabase') IS NULL CREATE DATABASE MyNewDatabase;"
Hope this helps!