user3807363
user3807363

Reputation: 143

how to check database already exists in sql server? and how stop the query if database already exists?

I have a query like this:

IF EXISTS(select name from sys.databases where name = 'AdventureWorks')
   use AdventureWorks

I want to use AdventureWorks if it already exists, but if it doesn't exists, I want to create the AdventureWorks database.

Help me please.

Upvotes: 0

Views: 874

Answers (1)

Roger Wolf
Roger Wolf

Reputation: 7722

if db_id('Test1') is not null
    set noexec on;

create database Test1;

set noexec off;

It seems, though, that you cannot switch the database context with USE in the same batch that creates it - MSSQL fires an error. So split it into 2 queries.

Upvotes: 1

Related Questions