Search code examples
c#sqldatabasedatatablecreate-table

Create Table SQL query - select table name from string


I'm attempting to programmatically create a SQL table. I can create a table with a query, this is no issue at all. But I'd like the table name to have some relevance to the data inserted into it, as it's being used for quotations and invoices. Data entered from a DataGridView will be inserted into it (probably via bulkcopy, or something similar).

using (SqlCeCommand command = new SqlCeCommand(
                  "CREATE TABLE table1' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))  

works perfectly. However I'd like this code to work:

using (SqlCeConnection con = new SqlCeConnection(@"Data Source=|DataDirectory|\LWADataBase.sdf"))
{
   con.Open();
   try
   {
      string tableName = "" + quotenameTxt.Text + "-" +firstTxt.Text+ "-" + surenameTxt.Text;

      using (SqlCeCommand command = new SqlCeCommand(
         "CREATE TABLE '"+tableName.ToString()+"' (Weight INT, Name NVARCHAR, Breed NVARCHAR)", con))
      {
         command.ExecuteNonQuery();
      }
   }
   catch (Exception ex)
   {
      MessageBox.Show(ex.Message);
   }
}

Any suggestions? I get an error (as expected) but are unsure what I need to do.

I'm using SqlCe (and before anyone says "BulkCopy isn't supported", I know, I've got a reference that allows it)

The error I get is :

There was an error parsing the query. [ Token line number = 1,Token line offset = 16,Token in error = 1-2-3 ]

// "1-2-3" being the textbox values.


Solution

  • Change the dashes to underscores or surround the entire table name with [square brackets]