Check if Database Exists

In creating a database you also need to check whether or not the database already exists. In order to do so, simply use the ‘if exists’ method and select the name of the database from sysdatabases.

[cc lang=”sql”]
IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N’SQLServerPlanet’)
CREATE DATABASE [SQLServerPlanet]
[/cc]

The code below will drop an existing database if it exists so be careful.
[cc lang=”sql”]
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N’SQLServerPlanet’)
DROP DATABASE [SQLServerPlanet]
[/cc]

An alternate method is to use the db_id to convert the db_name and see if it is null.
[cc lang=”sql”]
if db_id(‘SQLServerPlanet’) is not null
BEGIN
SELECT ‘database does exist’
END
ELSE
BEGIN
select ‘database does not exist’
END
[/cc]

2 comments
Mike 01 Mar 2017 at 5:02 pm

Thank you, exactly what I needed.

Gian Franco Cortegana 10 Dec 2014 at 5:51 am

Muchas gracias por el aporte … Me acaba de ayudar bastante.

Featured Articles

 Site Author

  • Thanks for visiting!
css.php