Animesh Ghosh
Animesh Ghosh

Reputation: 341

How do I solve syntax error in from clause?

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();
}

There shows an exception

Syntax error in FROM clause

Upvotes: 0

Views: 3161

Answers (3)

King King
King King

Reputation: 63377

I'm sure that your query is not SQL Server because it works OK in SQL Server query window. It could be Access SQL or My SQL, and you have to specify explicitly left join, right join or inner join. I think you want inner join in this case:

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

Upvotes: 1

Harris Yer
Harris Yer

Reputation: 291

Add is the Keyword of SQL, you can [] the field like a.[Add]

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

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064064

If it explicitly mentions from, then my guess would be that the SQL backend doesn't support aliases (the a). However, there are multiple problems:

  • the alias
  • the sql concatenation
  • the unnecessary adapter
  • the incorrect columns being read

I would suggest trying:

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"];
    }
}

Upvotes: 1

Related Questions