How to switch database context to newly created database?

SKINDER picture SKINDER · Mar 29, 2011 · Viewed 18.2k times · Source

I wrote a script to create a database:

1: USE master;
2: IF (db_id('myDB') is null)
3: CREATE DATABASE myDB;
4: USE myDB;

but it does not work... I got an error: Could not locate entry in sysdatabases for database 'myDB'. No entry found with that name. Make sure that the name is entered correctly. (Msg 911)

Where is my mistake?

Thanks.

ANSWER: go go go
USEFUL LINK: Without using GO, programmatically, you would need to make 2 separate database calls.

Answer

Mikael Eriksson picture Mikael Eriksson · Mar 29, 2011

It works if you separate your statements with a go

USE master;
go
IF (db_id('myDB') is null)
  CREATE DATABASE myDB;
go  
USE myDB;