Skip to content
 

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.

IF  NOT EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'SQLServerPlanet')
CREATE DATABASE [SQLServerPlanet]

The code below will drop an existing database if it exists so be careful.

IF  EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'SQLServerPlanet')
DROP DATABASE [SQLServerPlanet]

An alternate method is to use the db_id to convert the db_name and see if it is null.

if db_id('SQLServerPlanet') is not null
BEGIN
	SELECT 'database does exist'
END
ELSE
BEGIN
	select 'database does not exist'
END


Popular search terms:

post a comment OR Post Your Question on our ASK! Community!