Search code examples
c#mysqlasp.netsql-serverselect-query

Check if row exists from select count(*),where MS SQL query (asp.net)


i just want to set a variable based on if qno field row is empty or not i.e any entry has been inserted earlier or not

c# code:

cmd2 = new SqlCommand("Select COUNT(*) FROM " + tname + "WHERE qno = @qno", con99);
    cmd2.Parameters.AddWithValue("@qno", qno);
    if ((int)cmd2.ExecuteScalar() == 0) //V Studio shows error here
          qno_present = 0;
    else
        qno_present = 1;

Error:

an exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Additional information: Incorrect syntax near '='.


Solution

  • cmd2 = new SqlCommand("Select COUNT(*) FROM " + tname + "WHERE qno = @qno", con99);
    

    You need space before the WHERE clause

    cmd2 = new SqlCommand("Select COUNT(*) FROM " + tname + " WHERE qno = @qno", con99);