1

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?

5 Answers 5

6

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;
        }
    }
}
3
using(SqlConnection connection =
    new SqlConnection(connectionString))
{
connection.Open();
DataTable dt = connection.GetSchema();
connection.Close();
}

see here

1
1

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.

0

use information_schema

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.