Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SQL table name cannot start with numeric?

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

like image 855
user8074669 Avatar asked Nov 23 '25 23:11

user8074669


1 Answers

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 ---------------------------------^-----------------^
like image 52
Mureinik Avatar answered Nov 26 '25 12:11

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!