如何解决from子句中的语法错误?

时间:2013-08-02 07:07:13

标签: c# sql ado.net jet

string query = "select a.Name,a.Add from GroupDetails a join General b on a.ID=b.Id where b.AccCode='" + label1.text + "'";
OleDbCommand cmd = new OleDbCommand(query, con);
OleDbDataAdapter daName = new OleDbDataAdapter(cmd);

OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{

    txtName.Text = dr["a.Name"].ToString();
    txtAdd.Text = dr["a.Add"].ToString();
}

显示异常

  

FROM子句中的语法错误

3 个答案:

答案 0 :(得分:1)

如果它明确提到from,那么我的猜测是SQL后端不支持别名(a)。但是,存在多个问题:

  • 别名
  • sql concatenation
  • 不必要的适配器
  • 正在阅读的列不正确

我建议尝试:

const string query = "select GroupDetails.Name,GroupDetails.Add from GroupDetails join General on GroupDetails.ID=General.Id where General.AccCode=@accCode";

using(var cmd = new OleDbCommand(query, con))
{
    cmd.Parameters.AddWithValue("accCode", label1.text);
    using(var dr = cmd.ExecuteReader())
    {
        txtName.Text = (string)dr["Name"];
        txtAdd.Text = (string)dr["Add"];
    }
}

答案 1 :(得分:1)

我确定您的查询不是SQL Server,因为它在SQL Server查询窗口中正常工作。它可以是Access SQLMy SQL,您必须明确指定left joinright joininner join。在这种情况下,我认为你想要inner join

string query = "SELECT a.Name,a.Add FROM GroupDetails a INNER JOIN General b ON a.ID=b.Id WHERE b.AccCode='" + label1.text + "'";

答案 2 :(得分:0)

添加是SQL的关键字,你可以[]字段,如[。添加]

string query = "select a.Name,a.[Add] from GroupDetails a join General b on a.ID=b.Id where b.AccCode='" + label1.text + "'";