tags:

views:

138

answers:

5

I like to write c# code through which i like to check whether there is a table or not in sqlserver?

can any one give me a sample code for that?

+3  A: 
using(SqlConnection connection =
    new SqlConnection(connectionString))
{
connection.Open();
DataTable dt = connection.GetSchema();
connection.Close();
}

see here

ArsenMkrt
Here's the MSDN docs on GetSchema- http://msdn.microsoft.com/en-us/library/ms254934.aspx
RichardOD
A: 

use information_schema

select a.table_name from information_schema.tables a where table_name like ''

Umair Ahmed
+3  A: 

This query should give you the answer:

select count(id) from sysobjects where name = 'thetable' and type = 'U'

If count is 1 the table exists, if it is 0 it does not.

Wrapped into a method:

private bool TableExists(string tableName)
{
    using (SqlConnection conn = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand("select count(id) from sysobjects where name = @tableName and type = 'U'", conn))
        {
            cmd.Parameters.AddWithValue("@tableName", tableName);
            conn.Open();
            int count = (int)cmd.ExecuteScalar();
            conn.Close();
            return count == 1;
        }
    }
}
Fredrik Mörk
A: 

For newer SQL Server versions that support it (at least 2005 and 2008) you can write INFORMATION_SCHEMA queries. Eg. the following query (when run against your specific application database and not master) will return a row if there is a Users table.

SELECT * FROM information_schema.tables
WHERE TABLE_NAME = 'Users'
AND   TABLE_TYPE = 'BASE TABLE' -- could be 'VIEW'

or just return all the table names in your database like this:

SELECT TABLE_NAME FROM information_schema.tables
WHERE  TABLE_TYPE = 'BASE TABLE' -- could be 'VIEW'

I'm sure you've already got C# ADO code to run a query (or you could convert the above into a stored procedure). There's heaps of other useful information you can gather without worrying about all the arcane sysobjects parameters/columns/types.

CraigD
A: 

What you need is to query sysobject table in your SQLServer database to find the existence of a particular table/object in your database.

SELECT 1 AS Exists FROM dbo.sysobject where name = @tableName AND xtype = 'U'

open up a SQLConnection and wrap this query in SqlCommand object and execute it.

S M Kamran