Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 determining if an SQL database exists, etc.

Author  Topic 

BobLewiston
Starting Member

29 Posts

Posted - 2009-04-12 : 17:55:27
Could someone please give me the simplest possible C# code snippets / SQL queries to determine whether:

* a given SQL database exists,
* a given existing SQL database is accessible, and
* a given table exists within a given existing SQL database?

Thanks for whatever help anyone can provide.

cshah1
Constraint Violating Yak Guru

347 Posts

Posted - 2009-04-12 : 19:14:28
*a given existing SQL database is accessible
for this you have to create an ado.net connection object inside your C# code

if there is an exception thrown while opening connection to your sql db using try catch (specifically you have to catch sqlexception)

You can use the various metadata functions

* a given SQL database exists, use the following t sql
IF db_id('dbname') is not null

* a given table exists within a given existing SQL database
IF object_id('object_name', 'U') is not null -- for table

Go to Top of Page

BobLewiston
Starting Member

29 Posts

Posted - 2009-04-12 : 21:13:48
cshah1:

Please pardon what I'm sure is a stupid question, but I'm a newbie stumbling around in the dark:

Are these SQL queries or VB snippets? If it's VB, do you know where I can find this in C#?
Go to Top of Page

cshah1
Constraint Violating Yak Guru

347 Posts

Posted - 2009-04-12 : 21:44:39
Bob,

IF db_id('dbname') is not null
Print 'db exists'
Go

IF object_id('object_name', 'U') is not null
Print 'table exists'
Go
these are T-SQL statements you should be able to run them on SQL query editor




Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-04-15 : 13:35:06
can i ask why you want to check existence of db in vb code?
Go to Top of Page
   

- Advertisement -