Getting "Incorrect syntax near"-error with SqlDataReader

4k views Asked by At

I'm getting error and I don't know what's wrong with the code, so If anyone can help me I would be grateful.

Error:

Incorrect syntax near ','.

and the highlighted line is

rdr = cmd.ExecuteReader();

Code:

cn.Open();
string query = "SELECT * FROM dbo.ispiti WHERE poID=@poID, sgID=@sgID, npID=@npID";

SqlCommand cmd = new SqlCommand(query, cn);

cmd.Parameters.AddWithValue("@poID", pr);
cmd.Parameters.AddWithValue("@sgID", pr1);
cmd.Parameters.AddWithValue("@npID", pr2);

SqlDataReader rdr;

try
{
    rdr = cmd.ExecuteReader();

    if (rdr.Read())
    {
        MessageBox.Show("Well done!");
    }
}
catch(exception ex)
{
    MessageBox.Show("Error!");
}
finally
{
    cn.Close();
}
2

There are 2 answers

1
Chui Tey On BEST ANSWER

There is an error in your SQL statement. You should change

string query = "SELECT * FROM dbo.ispiti WHERE poID=@poID, sgID=@sgID, npID=@npID";

to

string query = "SELECT * FROM dbo.ispiti WHERE poID=@poID AND sgID=@sgID AND npID=@npID";
0
Soner Gönül On

You can't use comma in WHERE clause. You need to use logical operations like AND or OR like;

WHERE poID=@poID AND sgID=@sgID AND npID=@npID

This clause takes search condition after it and there is no syntax for comma.

By the way, use using statement to dispose your connections, commands and readers automatically instead of calling Dispose or Close methods manually.

Also don't use AddWithValue method. It may generate unexpected results sometimes. Use Add method overloads to specify your parameter type and it's size.