Mehdi Bugnard
Mehdi Bugnard

Reputation: 3979

How to create and use database directly after creation in SQL Server?

I created a sql script to check if a database already exist, if it already exists it deletes and re-creates.
After I would like to connect it directly after its creation for creating tables ..

Here is my code but it does not work, it produces the following error:

Msg 911, Level 16, State 1, Line 10
Database 'Arms2' does not exist. Make sure that the name is entered correctly.

My script

IF EXISTS (select * from sys.databases where name = 'Arms2')
BEGIN 
    DROP DATABASE Arms2
    PRINT 'DROP DATABASE Arms2'
END
    CREATE DATABASE Arms2;
    PRINT 'CREATE DATABASE Arms2'

USE Arms2

CREATE TABLE .....

Upvotes: 5

Views: 8415

Answers (1)

AdaTheDev
AdaTheDev

Reputation: 147334

Put a GO statement after the CREATE...

...
CREATE DATABASE Arms2;
PRINT 'CREATE DATABASE Arms2'
GO
USE Arms2

Upvotes: 12

Related Questions