Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server: Having clause with variables
    primarykey
    data
    text
    <p>I'm working on a stored procedure for an academic institution that would allow advisors to filter their student lists by a number of criteria. Recently, the advisors asked me to give them the option of filtering students by GPA. This was perfectly easy until they asked for an option to determine the inequality.</p> <p>Here's a truncated copy of the query I'm using, and the corresponding error message in SQL.</p> <pre><code>DECLARE @Inequality CHAR(2) SET @Inequality = '&gt;=' DECLARE @Gpa DECIMAL(3,1) SET @Gpa = 2.0 SELECT DISTINCT mem.StudentID, SUM(GradePointValue * Credits) / SUM(Credits) AS GPA FROM &lt;snip&gt; WHERE &lt;snip&gt; GROUP BY mem.StudentID HAVING CASE @Inequality WHEN '&gt;=' THEN SUM(GradePointValue * Credits) / SUM(Credits) &gt;= @Gpa WHEN '&gt;' THEN SUM(GradePointValue * Credits) / SUM(Credits) &gt; @Gpa WHEN '&lt;' THEN SUM(GradePointValue * Credits) / SUM(Credits) &lt; @Gpa WHEN '&lt;=' THEN SUM(GradePointValue * Credits) / SUM(Credits) &lt;= @Gpa END ORDER BY GPA desc </code></pre> <p>When I try to execute this query, SSMS gives me the following error message: <code>Incorrect syntax near '&gt;'.</code>, referencing the first line of the <code>CASE</code> statement in the <code>HAVING</code> clause, <code>&gt;= @GPA</code></p> <p>I've tried rewriting the <code>HAVING</code> clause to:</p> <pre><code>HAVING SUM(GradePointValue * Credits) / SUM(Credits) CASE @Inequality WHEN '&gt;=' THEN &gt;= ... END @Gpa </code></pre> <p>This produces another error message: <code>Incorrect syntax near the keyword 'CASE'.</code></p> <p>I know I could copy and paste the entire SQL query four times and change only the inequality in the <code>HAVING</code> clause in each query, but that's messy (not that this isn't -- it just doesn't smell as bad to me) and I'd like to avoid it if I can. Is there any way for me to pull off my attempt above?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload