Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a database exists in SQL Server?

What is the ideal way to check if a database exists on a SQL Server using TSQL? It seems multiple approaches to implement this.

like image 570
Ray Avatar asked Mar 24 '09 19:03

Ray


People also ask

How do you check if a database already exists in SQL Server?

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.

How do I check if a database already exists?

A simple way to check if a database exists is: SHOW DATABASES LIKE 'dbname'; If database with the name 'dbname' doesn't exist, you get an empty set. If it does exist, you get one row.

What is the use of Information_schema in SQL Server?

INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such as the name of a database or table, the data type of a column, or access privileges. Other terms that are sometimes used for this information are data dictionary and system catalog.


1 Answers

Actually it's best to use:

IF DB_ID('dms') IS NOT NULL    --code mine :)    print 'db exists' 

See https://docs.microsoft.com/en-us/sql/t-sql/functions/db-id-transact-sql and note that this does not make sense with the Azure SQL Database.

like image 67
Eduardo Avatar answered Sep 20 '22 19:09

Eduardo