MS SQL - Create database and use it right away

By xngo on October 29, 2019

For MS SQL Server, I wrote a SQL script to create a database called Test and then use it right away. When I execute the script, it is showing the following error message.

Msg 911, Level 16, State 1, Server MyComputer\SQLEXPRESS, Line 3 Database 'Test' does not exist. Make sure that the name is entered correctly.

Here is my script.

USE master;
CREATE DATABASE Test;
USE Test;

Solution

The solution is to put a GO statement after the CREATE statement. GO will signal the end of the batch of Transact-SQL statements. Here is how I rewrite my SQL statements.

USE master;
CREATE DATABASE Test;
GO
USE Test;

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.