ashish ashish - 4 months ago 23
ASP.NET (C#) Question

Error in create table command- Incorrect syntax near

I want to create a table name based on session's variable name

(session variable is email id of a student and sid of that student will be the table name which I want to create)

NOTE: sid is fetching fine..

Here's the code

SqlConnection con99 = new SqlConnection(con100);
String email = Session["sname"].ToString();
SqlCommand cmd = new SqlCommand("select id from students where email='"
+ email + "'", con99);
sid = cmd.ExecuteScalar().ToString(); //as sid is int
using (SqlCommand command = new SqlCommand("CREATE TABLE " + sid +
"(sno int, qpname nvarchar(500), mobtained int, tmarks int);", con99))

here is the error message pic

variable sid is also being created-pic


You must put brackets around your table name if you are naming it with a number. So your script must end up like this when evaluated:

CREATE TABLE [2] (sno int, qpname nvarchar(500), mobtained int, tmarks int);

Frankly, I'm surprised that is allowed. It may be a feature of newer versions of SQL Server.

A better way to create database objects is with the SQL Server Management Objects (SMO) libraries. Much less chance to make syntax errors:

An example from here

Server srv = new Server("(local)");
Database db = srv.Databases["AdventureWorks2012"];

Table tb = new Table(db, "Test Table");
Column col1 = new Column(tb, "Name", DataType.NChar(50));
Column col2 = new Column(tb, "ID", DataType.Int);