johzz_o2 johzz_o2 - 3 years ago 176
C# Question

can't fix syntax error in Inner Join query in c#

I am trying to get the results of the query below and display it in a listBox but I keep getting this error : Syntax Error near 'a'. Here is my code:

SqlConnection con = new SqlConnection(@"Data Source=JOHZZ\SQLEXPRESS;
Initial Catalog=parking;
Persist Security Info=True;
User ID=SA;
Password=Roses2004");
SqlCommand c3 = new SqlCommand("SELECT targa" +
"FROM mjete AS m INNER JOIN abonimi_mjet AS a" +
"ON m.mjeti_id = a.mjeti_id" +
"WHERE a.statusi = 'PASIV'" +
"AND m.klient_id = @idK", con);
con.Open();
c3.Parameters.AddWithValue("@idK",idK);
SqlDataReader reader2 = c3.ExecuteReader();
while (reader2.Read())
{
listBoxTarga.Items.Add(reader2.GetString(0));
}

reader2.Close();
con.Close();


I tried the same query in SQL Server Management Studio and it worked fine .
Thanks in advance for your help .

Answer Source

You need a space between your lines. Using the + symbol adds them together as one string, just add a space at the end of each string.

SqlCommand c3 = new SqlCommand("SELECT targa " +
       "FROM mjete AS m INNER JOIN abonimi_mjet AS a " +
       "ON m.mjeti_id = a.mjeti_id " +
       "WHERE a.statusi = 'PASIV' " +
       "AND m.klient_id = @idK", con);

What you have now results in this string as the line breaks in your c# file are not string line breaks.

"SELECT targaFROM mjete AS m INNER JOIN abonimi_mjet AS aON m.mjeti_id = a.mjeti_idWHERE a.statusi = 'PASIV'AND m.klient_id = @idK"

Side notes

You should wrap your SqlConnection instance in a using block to ensure it is always closed/disposed when you are done using it (even in the event of an Exception). The same goes for your SqlDataReader instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download