创建 table 命令时出错 - 附近的语法不正确
Error in create table command- Incorrect syntax near
我想根据会话的变量名创建一个table名称
(会话变量是学生的电子邮件 ID,该学生的 sid 将是我要创建的 table 名称)
注意:sid 获取正常..
这是代码
SqlConnection con99 = new SqlConnection(con100);
con99.Open();
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))
command.ExecuteNonQuery();
con99.Close();
如果您用数字命名,则必须将您的 table 名字括起来。所以你的脚本在评估时必须像这样结束:
CREATE TABLE [2] (sno int, qpname nvarchar(500), mobtained int, tmarks int);
坦率地说,我很惊讶这是允许的。它可能是 SQL 服务器较新版本的功能。
创建数据库对象的更好方法是使用 SQL 服务器管理对象 (SMO) 库。出现语法错误的机会更少:
一个例子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);
tb.Columns.Add(col1);
tb.Columns.Add(col2);
tb.Create();
第一个是错误的,接下来的两个不是:
create table 2 (id int)
create table [2] (id int)
create table ID_2 (id int)
请参阅名为 "The first character must be one of the following" here 的部分。
我想根据会话的变量名创建一个table名称
(会话变量是学生的电子邮件 ID,该学生的 sid 将是我要创建的 table 名称)
注意:sid 获取正常..
这是代码
SqlConnection con99 = new SqlConnection(con100);
con99.Open();
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))
command.ExecuteNonQuery();
con99.Close();
如果您用数字命名,则必须将您的 table 名字括起来。所以你的脚本在评估时必须像这样结束:
CREATE TABLE [2] (sno int, qpname nvarchar(500), mobtained int, tmarks int);
坦率地说,我很惊讶这是允许的。它可能是 SQL 服务器较新版本的功能。
创建数据库对象的更好方法是使用 SQL 服务器管理对象 (SMO) 库。出现语法错误的机会更少:
一个例子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);
tb.Columns.Add(col1);
tb.Columns.Add(col2);
tb.Create();
第一个是错误的,接下来的两个不是:
create table 2 (id int)
create table [2] (id int)
create table ID_2 (id int)
请参阅名为 "The first character must be one of the following" here 的部分。