Check if Database Exists
-
Posted on May 23, 2010 by Derek Dieter
-
8
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]
- Comments (RSS)
- Trackback
- Permalink