What's the easiest way to check if a database exists in MSSQL using VB.NET?

I am trying to check if a database exists on Microsoft SQL Server, what's the easiest way to do this? I just want it to return true or false, then I would create the database if it doesn't exist. Any help would be appreciated, thanks.

+3


source to share


3 answers


Connect to the system db (master, msdb, tempdb or model) - because you can be sure they exist! Then you can select the database list 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 whichever provider you are using) you should automatically connect to the default database (which is "wizard" by default)

+4


source


Try below

Declare @Dbname varchar(100)

SET @Dbname = 'MASTER'

if exists(select * from sys.databases where name = @Dbname)
select 'true'
else 
select 'false'

      



this is specifically for SQL Server

+3


source


You can try the following query:

select * from sys.databases where [name] = <name of database>

      

0


source







All Articles