How to check if a database exists in SQL Server? How to check if a database exists in SQL Server? sql-server sql-server

How to check if a database exists in SQL Server?


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.


From a Microsoft's script:

DECLARE @dbname nvarchar(128)SET @dbname = N'Senna'IF (EXISTS (SELECT name FROM master.dbo.databases WHERE ('[' + name + ']' = @dbname OR name = @dbname)))


IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'YourDatabaseName')  Do your thing...

By the way, this came directly from SQL Server Studio, so if you have access to this tool, I recommend you start playing with the various "Script xxxx AS" functions that are available. Will make your life easier! :)