Hi guys I keep getting this error and I can’t figure it out. It works when I run the query in the database tool but not when it’s in my Microsoft web dev.
The error i get is:
An expression of non-boolean type specified in a context where a condition is expected, near ‘GROUP’.
Code:
Session["string"] = "answer ='Male'"; Session["count"] = 1; myCommandSearch = new SqlCommand("SELECT userId FROM UserAnswer WHERE @SEARCHVARIABLES GROUP by userId HAVING COUNT(*) = @VARIABLECOUNT", myConnection); myCommandSearch.Parameters.AddWithValue("@SEARCHVARIABLES", Session["string"]); myCommandSearch.Parameters.AddWithValue("@VARIABLECOUNT", Session["count"]); SqlDataReader myReaderSearch = myCommandSearch.ExecuteReader();
Thanks in Advance for the help.
Advertisement
Answer
This is your query:
SELECT userId FROM UserAnswer WHERE @SEARCHVARIABLES GROUP by userId HAVING COUNT(*) = @VARIABLECOUNT;
Parameters can be used to replace literal values. They cannot be used to replace:
- Column names
- Table names
- Databases
- Expressions
- Function names
- And anything else that is not a constant
So, @SEARCHVARIABLES
would seems to be a string. Let’s say it is something like this: userId IN (1, 2, 3)
. Then the query would be:
SELECT userId FROM UserAnswer WHERE 'userId IN (1, 2, 3)' GROUP by userId HAVING COUNT(*) = @VARIABLECOUNT;
A string is not allowed in that context. Hence, you are getting an error.