Saturday, June 12, 2010

Check to see if a table exists in SQL Server using C#

To do database related task we may sometime need to check if the sql table exists or not in the SQL Database. By the following code we can simply check this::

        string tblnm = 'your-table-name';
        string str = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + tblnm + "'";
        SqlCommand myCommand = new SqlCommand(str, connection);
        SqlDataReader myReader = null;
        int count = 0;

        try
        {
            connection.Open();
            myReader = myCommand.ExecuteReader();
            while (myReader.Read())           
                count++;
           
            myReader.Close();
            connection.Close();
        }
        catch (Exception ex) { Response.Write(ex.ToString()); }
        if (count == 0)
            Label1.Text = "Table doesn't exists";
        else
            Label1.Text = "Table exists";


// by returning true/false based on count u can do your job also


We can check the table exists or not in another way.......
Suppose we want to count the row number of a table if that table exists. we can do so by following  way::


string tblnm = 'your-table-name';
string sql = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + tblnm + "]'))";
sql += " SELECT count(*) FROM " +
tblnm;

connection.Open();
SqlCommand sqlcom = new SqlCommand(sql, connection);
SqlDataReader dr = sqlcom.ExecuteReader();

int c = -1;
while (dr.Read())
{
    c = (int)dr.GetValue(0);
}
connection.Close();
 

if (c != -1)
     Label2.Text = c.ToString()+" rows";
else
     Label2.Text = "table not exists";




2 comments:

  1. Thanks for the sharing about .Net program. it's really nice. keep it up more post. ASP.Net Application Development

    ReplyDelete
  2. your welcome sukumar. Actually when i develop project and face any problem and after the solution i feel it may help other programmers. For this i listed in the blog. If it helps any single person, its all my pleasure.

    ReplyDelete