Nyawk Nyawk
Nyawk Nyawk

Reputation: 45

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

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

Answers (3)

F0r3v3r-A-N00b
F0r3v3r-A-N00b

Reputation: 3003

You can try the following query :

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

Upvotes: 0

user4622594
user4622594

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

Indra Prakash Tiwari
Indra Prakash Tiwari

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

Related Questions