0

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.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Ramy Mahrous
0

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

CHECK DB EXIST OR NOT:

if NOT exists(select 1 from master.dbo.sysdatabases where name =
'yourDB')
begin
print 'DB does not exists';
end

Database is accessible:

Begin
Declare @Exist Int;
Set @Exist = HAS_DBACCESS('yourDB') 
IF @Exist = 1 
Print 'Accessible';
Else
IF @Exist = 0 
Print 'Not Accessible';
Else
Print 'Invalid Database';
End

Table Exists/Not:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))

Just replace TableName by your table name.

OBJECT_ID is more powerful. If you wanna know more then google it.

HAPPY PROGRAMMING....

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.