Why can't the SQL table name start with a number?

I am new to C#

and SQL

.

Using the following code, I am trying to create a new table and everything went well as I wanted, but the problem is this: using textBox

, if I name a table that starts with digits ( 123MytableName

), it gives the error "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 one but it didn't help.

Does anyone know how to fix it to create a table that starts with numbers?

thank

+3


source to share


1 answer


You can escape the table name by including it with []

:



MySQLCommand.CommandText = "CREATE TABLE ["+textBox1.Text+"] (Col1 int, Col2 varchar(50), Col money)";
// Here ---------------------------------^-----------------^

      

+1


source







All Articles