What is the ideal way to check if a database exists on a SQL Server using TSQL? It seems multiple approaches to implement this.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With