Note that there are some explanatory texts on larger screens.

plurals
  1. POOrder by with case statement fails only when using a parameter with error ORDER BY items must appear in the select list
    primarykey
    data
    text
    <p>I have a stored proc that consists of 3 queries joined by unions. This works. It currently has an order by value set like so:</p> <pre><code> ORDER BY [CategoryTypeID], [SortOrder], [Name] </code></pre> <p>I want to make this dynamic so i tried using a case statement like this:</p> <pre><code> ORDER BY CASE WHEN @sort = 0 then [CategoryTypeID] ELSE [SortOrder] end </code></pre> <p>However, when i do this sql complains that order by items must appear in the select list if the statement contains union... etc</p> <p>However, if i change the above to avoid using the parameter:</p> <pre><code>ORDER BY CASE WHEN 0 = 0 then [CategoryTypeID] ELSE [SortOrder] end </code></pre> <p>That works. Why is it unhappy when i use a parameter when that parameter is not actually being used in the order by? I even tried including the parameter in the select statements but it still gave me the same error.</p> <p>I also tried doing case @sort when 1 etc but got the same results. And I did declare the parameter in my stored proc - @sort int = 0</p> <p>This is MSSQL 2012 express</p> <p>Edit - for additional clarity</p> <pre><code> ORDER BY CASE WHEN @sort = 0 then [SortOrder] ELSE [CategoryTypeID] end </code></pre> <p>and</p> <pre><code>ORDER BY CASE WHEN @sort = 0 then [CategoryTypeID] ELSE [CategoryTypeID] end </code></pre> <p>Both of those statements fail as well with a 'must appear in the select list' error. And i was not trying to use both of those statements at the same time. Just giving them as examples that the columns themselves dont appear to be an issue. It using the parameter that appears to be an issue, even though the paramter itself is not being selected or being sorted.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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