I am wondering if there is an elegant way to check for the existence of a DB? In brief, how do test the connection of a db connection string?
Thanks
To cover the range of possibilities (server doesn't exist, database doesn't exist, no login, no permissions, server down, etc) - the simplest idea is simply to try to connect as normal, and perform something trivial - SELECT GETDATE()
for example. If you get an exception, there is a problem!
There are times (especially when dealing with out-of-process systems) when try/catch
is the most pragmatic option.
try
IF NOT EXISTS(SELECT * FROM sys.databases WHERE [name] = @name)
CREATE DATABASE @name;
GO
or
IF db_id(@name) IS NOT NULL
CREATE DATABASE @name;
GO
or SqlConnection.ChangeDatabase(String). I think it could use less sql server resources then new connection attempt.