SKINDER
SKINDER

Reputation: 1020

How to switch database context to newly created database?

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.

Upvotes: 2

Views: 33150

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

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; 

Upvotes: 7

RQDQ
RQDQ

Reputation: 15569

Add a GO statement after line 3. That will force execution of the previous script.

Upvotes: 4

Related Questions