0

How can I check if a table already exists before creating a 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 * 
                                              FROM INFORMATION_SCHEMA.TABLES 
                                              WHERE 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();}
3

2 Answers 2

1

Sql Server Compact supports the INFORMATION_SCHEMA views

using (SqlCeConnection conn = new SqlCeConnection(connStr))
{
    conn.Open();    
    SqlCeCommand cmd = new SqlCeCommand(@"SELECT TOP 1 * 
                                          FROM INFORMATION_SCHEMA.TABLES 
                                          WHERE 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 it seems that the TOP 1 instruction is not accepted. However, given the WHERE clause it should make no difference using it or not so, to make it work just change the query to

SqlCeCommand cmd = new SqlCeCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES 
                                      WHERE TABLE_NAME = @tname", conn);

SECOND EDIT Looking at the code that creates the table.
(It is In chat, I suggest to add it to the question for completeness)

using (SqlCeCommand command = new SqlCeCommand( 
        "CREATE TABLE ['" + tableName + "'] " + 
        "(Weight INT, Name NVARCHAR, Breed NVARCHAR)", con)) 

The single quotes around the tableName variables becomes part of the name of the table. But the check for table exists doesn't use the quotes. And your code fall through the path that tries to create again the table with the quotes. Just remove the quotes around the name. They are not needed.

Sign up to request clarification or add additional context in comments.

16 Comments

There was an error parsing the query. [ Token line number = 1,Token line offset = 12,Token in error = 1 ] is the error i get from this code
I have no error testing with a database with Sql Server Compact 4.0
Well, I cannot test with 3.5 now. But try to remove the TOP 1 and leave only SELECT * FROM INFORMATION_SCHEMA.TABLES .... this should be absolutely correct unless the INFORMATION_SCHEMA views are not supported in 3.5.
Ok just downloaded and tested with the 3.5 bits. It is the TOP 1. Remove it and it should work fine
I've done as you said but its not actually doing anything. Regardless of whether the table exists it just gives me the "table does not exist" messagebox.
|
0

You can use the SqlClientConnection to get list of all objects in the db.

private void checkTable()
{
    string tableName = quotenameTxt.Text + "-" + firstTxt.Text + "-" + surenameTxt.Text;
    string connStr = @"Data Source=|DataDirectory|\LWADataBase.sdf";

    using (SqlCeConnection conn = new SqlCeConnection(connStr))
    {
        bool isTableExist = conn.GetSchema("Tables")
                                .AsEnumerable()
                                .Any(row => row[2] == tableName);
    }

    if (!isTableExist)
    {
        MessageBox.Show("No such data table exists!");
    }
    else
    {
        MessageBox.Show("Such data table exists!");
    }
}

Source: https://stackoverflow.com/a/3005157/1271037

2 Comments

"Specified method is not supported"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.