I am new to C# and SQL.
Using the following code I am trying to create new table and all went good as I wanted but the problem is: using textBox if I name a table starts with numbers (123MytableName) it throws error saying " Incorrect syntax near '123MytableName'"
using (SqlConnection MyConnection = new SqlConnection())
using (SqlCommand MySQLCommand = new SqlCommand())
{
MyConnection.ConnectionString = " Data Source=localhost; Initial Catalog=TestDB ;Integrated Security=true;Max Pool Size=1024; Pooling=true";
MyConnection.Open();
MySQLCommand.CommandText = "CREATE TABLE "+textBox1.Text+" (Col1 int, Col2 varchar(50), Col money)";
MySQLCommand.Connection = MyConnection;
MySQLCommand.ExecuteNonQuery();
}
I read this but it did not help.
Anyone knows how to fix it so I can create table which starts with numbers?
Thank you
You can escape the table's name by enclosing it with []:
MySQLCommand.CommandText = "CREATE TABLE ["+textBox1.Text+"] (Col1 int, Col2 varchar(50), Col money)";
// Here ---------------------------------^-----------------^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With