Using C#, how do you check if a table exists in SQL?


hi, working on project transfers data dbf files sql.  need check see if tables proposed table name exist in sql.  have code check if table exists , deletes it.  however, somehow figure out if table exists, return value based on existence, , give user option of either dropping , replacing table if exists, or stopping process avoid replacement.  below code have check if table exists.  have been trying work executescalar have never worked not sure how use properly.  appreciated.

  using (sqlconnection myconnection = new sqlconnection("server=cmiclosed2;database=" + database + ";trusted_connection=true;"))  {    myconnection.open();  							    stringbuilder exists = new stringbuilder("if exists (select * dbo.sysobjects id = object_id('[dbo].[" + sqltablename + "]'))"      + " drop table [dbo].[" + sqltablename + "]");      string sql2 = exists.tostring();    sqlcommand cmd2 = new sqlcommand(sql2, myconnection);    cmd2.executenonquery();    }  

hi nkarek23,

please try code below:

    int32 newprodid = 0;     string sql = "select count(*) isexists dbo.sysobjects id = object_id('[dbo].[" + sqltablename + "]')";     using (sqlconnection conn = new sqlconnection("server=cmiclosed2;database="+ database +";trusted_connection=true;"))     {       sqlcommand cmd = new sqlcommand(sql, conn);           try       {         conn.open();         newprodid =(int32)cmd.executescalar();       }       catch (exception ex)       {                 messagebox.show(ex.message);       }     }     //get result value: 1-exist; 0-not exist;     messagebox.show(newprodid.tostring());



best regards,
stephanie lv




SQL Server  >  SQL Server Migration



Comments

Popular posts from this blog

Conditional formatting a graph vertical axis in SSRS 2012 charts

Register with Power BI failed

SQL server replication error Cannot find the dbo or user defined function........