none
How to check if a SQL Server 2008 R2 table exists by using C#

คำตอบ

  • So I figured this out for the most part.  I just added this query, it works fine:

     

     

          using (SqlConnection myConnection = new SqlConnection("Server=cmiclosed2;Database=" + Database + ";Trusted_Connection=True;"))
          {
           myConnection.Open();
    
           StringBuilder exists = new StringBuilder("IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id('[dbo].[" + SQLTableName + "]'))"
            + " drop table [dbo].[" + SQLTableName + "]");
    
           string sql2 = exists.ToString();
           SqlCommand cmd2 = new SqlCommand(sql2, myConnection);
           cmd2.ExecuteNonQuery();
          }
    

     Where database is the name of the database in SQL and the SQLTableName is the name of the SQL table.


    • ทำเครื่องหมายเป็นคำตอบโดย nkarek23 13 กรกฎาคม 2554 14:43
    13 กรกฎาคม 2554 14:43

ตอบทั้งหมด

  • So I figured this out for the most part.  I just added this query, it works fine:

     

     

          using (SqlConnection myConnection = new SqlConnection("Server=cmiclosed2;Database=" + Database + ";Trusted_Connection=True;"))
          {
           myConnection.Open();
    
           StringBuilder exists = new StringBuilder("IF EXISTS (SELECT * FROM dbo.sysobjects where id = object_id('[dbo].[" + SQLTableName + "]'))"
            + " drop table [dbo].[" + SQLTableName + "]");
    
           string sql2 = exists.ToString();
           SqlCommand cmd2 = new SqlCommand(sql2, myConnection);
           cmd2.ExecuteNonQuery();
          }
    

     Where database is the name of the database in SQL and the SQLTableName is the name of the SQL table.


    • ทำเครื่องหมายเป็นคำตอบโดย nkarek23 13 กรกฎาคม 2554 14:43
    13 กรกฎาคม 2554 14:43
  • If you're using C#, try this

    private bool TableExists(string tableName, SqlConnection cnn)

    {

        DataTable dt = cnn.GetSchema("Tables");

        dt.PrimaryKey = new DataColumn[] { dt.Columns["Table_Name"] };

        return (dt.Rows.Find(tableName != null));

    }

    If you could have the same table name in different schemas, add "Schema" to the primary key.


    John Carroll


    • แก้ไขโดย llorrac 23 กุมภาพันธ์ 2555 15:07
    23 กุมภาพันธ์ 2555 15:07