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.

Recommended Answers

All 2 Replies

* 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....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.