简体   繁体   中英

An expression of non-boolean type specified in a context where a condition is expected, near 'GROUP'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM