0

我的 SqlCommand 有问题,我打开页面时遇到错误:

System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.

我找不到问题,因为在整个项目和标题中只找到了一次“Van”。这是我在 Page_Load 中的代码:

   using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
            {
                var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
                cmd.Connection.Open();
                var sqlReader = cmd.ExecuteReader();
                while (sqlReader.Read())
                {

                    String result = sqlReader.GetString(0);
                    DropDownList1.DataBind();
                    DropDownList1.Items.FindByValue(result).Selected = true;
                    //Fill some data like : string result = sqlReader("SomeFieldName");
                }
                sqlReader.Close();
                cmd.Connection.Close();
                cmd.Dispose();
            }

数据库连接字符串是正确的,因为它适用于我的所有其他页面。我正在尝试获取员工工作的部门,以便他/她只能查看他们自己部门的备忘录。

4

3 回答 3

1

您需要关闭提供的姓氏后的括号。

SELECT (SELECT Memo_ID, Dep_Name FROM Department 
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName 
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )

这是它的样子:

  using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
        {
            var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
            cmd.Connection.Open();
            var sqlReader = cmd.ExecuteReader();
            while (sqlReader.Read())
            {

                String result = sqlReader.GetString(0);
                DropDownList1.DataBind();
                DropDownList1.Items.FindByValue(result).Selected = true;
                //Fill some data like : string result = sqlReader("SomeFieldName");
            }
            sqlReader.Close();
            cmd.Connection.Close();
            cmd.Dispose();
于 2012-05-29T12:02:53.380 回答
0

您需要引用姓氏。您可能也想转换为参数化查询。

于 2012-05-29T12:01:00.800 回答
0

我本来希望您的WHERE条款将User.Identity.Name引号括起来:

WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...

van ”可以在用户名中吗?

这也不是一个非常安全的查询——但 SQL 注入是另一个问题!

于 2012-05-29T12:02:01.207 回答