Reputation: 45
I'm trying to check if a database exists in the Microsoft SQL Server, what's the simplest way to do that? I just want it to return a true or false value then I would create a database if it doesn't exist. Any help would be appreciated, thanks.
Upvotes: 4
Views: 11914
Reputation: 3003
You can try the following query :
select * from sys.databases where [name] = <name of database>
Upvotes: 0
Reputation:
Connect to a system-db (master, msdb, tempdb or model) - because you can be sure that they exist! Then you can select the list of database like this:
select * from sys.databases
or if you want to know if a specific db exists:
select * from sys.databases where name = 'NameOfYourDb'
If you connect without a database name in your connection string (belongs to which provider you are using) you should automatically be connect to your default database (which is "master" by default)
Upvotes: 6
Reputation: 1067
Try below one
Declare @Dbname varchar(100)
SET @Dbname = 'MASTER'
if exists(select * from sys.databases where name = @Dbname)
select 'true'
else
select 'false'
this is specially for SQL Server
Upvotes: 4