c# - Check if table name exists SQL -



c# - Check if table name exists SQL -

how can check if table exists before creating new one?

updated code:

private void checktable() { string tablename = quotenametxt.text + "_" + firsttxt.text + "_" + surenametxt.text; string connstr = @"data source=|datadirectory|\lwadatabase.sdf"; // sqlceconnection conn = new sqlceconnection(connstr); // if (conn.state == connectionstate.closed) { conn.open(); } using (sqlceconnection conn = new sqlceconnection(connstr)) { conn.open(); sqlcecommand cmd = new sqlcecommand(@"select * information_schema.tables table_name = @tname", conn); cmd.parameters.addwithvalue("@tname", tablename); sqlcedatareader reader = cmd.executereader(); if(reader.read()){ messagebox.show("table exists");} else{ messagebox.show("table doesn't exist"); createtable();}

sql server compact supports information_schema views

using (sqlceconnection conn = new sqlceconnection(connstr)) { conn.open(); sqlcecommand cmd = new sqlcecommand(@"select top 1 * information_schema.tables table_name = @tname", conn); cmd.parameters.addwithvalue("@tname", tablename) sqlcedatareader reader = cmd.executereader(); if(reader.read()) console.writeline("table exists"); else console.writeline("table doesn't exist"); }

edit in version 3.5 seems top 1 instruction not accepted. however, given clause should create no difference using or not so, create work alter query

sqlcecommand cmd = new sqlcecommand(@"select * information_schema.tables table_name = @tname", conn);

second edit looking @ code creates table. (it in chat, suggest add together question completeness)

using (sqlcecommand command = new sqlcecommand( "create table ['" + tablename + "'] " + "(weight int, name nvarchar, breed nvarchar)", con))

the single quotes around tablename variables becomes part of name of table. check table exists doesn't utilize quotes. , code fall through path tries create 1 time again table quotes. remove quotes around name. not needed.

c# sql database sql-server-ce

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

c# - Create a Notification Object (Email or Page) At Run Time -- Dependency Injection or Factory -

Set Up Of Common Name Of SSL Certificate To Protect Plesk Panel -