0

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.

2
  • 1
    So what's the problem? Commented Aug 9, 2014 at 14:25
  • Not sure: CREATE DATABASE AdventureWorks WHERE NOT EXISTS(select name from sys.databases where name = 'AdventureWorks') Commented Aug 9, 2014 at 14:27

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.