Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your problem is the use of constants in the query. You are sorting by constant strings, rather than columns. I think you are mixing up dynamic SQL and regular SQL.</p> <p>To get the names, you would want to use:</p> <pre><code>SELECT ROW_NUMBER() OVER (Order by CASE WHEN @sortBy='datecreate' THEN datecreate WHEN @sortBy='id' THEN id WHEN @sortBy='DisplayName' THEN DisplayName END, </code></pre> <p>However, this won't work, because of the type conflict. You have two options. First, either convert all the types to string with the right sort order (YYYY-MM-DD for dates, zero pads for numbers). Or, since this is a stored procedure, create a separate query for each one.</p> <p>The issue is that you might get everything as a string, but I'm still not sure how to get the ASC and DESC in. I think you will need two queries for this, which is feasible since this is inside a stored procedure.</p> <p>I like Aaron's answer, but I think it can be improved.</p> <pre><code>WITH Ordering AS ( SELECT ROW_NUMBER() OVER (ORDER BY (case when @sortBy = 'datecreate' and @sortdirection = 'ASC' then datecreate end), (case when @sortBy = 'datecreate' and @sortdirection = 'DESC' then datecreate end) desc, (case when @sortBy = 'id' and @sortdirection = 'ASC' then id end), (case when @sortBy = 'id' and @sortdirection = 'DESC' then id end) desc, (case when @sortBy = 'DisplayName' and @sortdirection = 'ASC' then DisplayName end), (case when @sortBy = 'DisplayName' and @sortdirection = 'DESC' then DisplayName end) desc ) as rn, dbo.x1.*, dbo.x2.* FROM dbo.x1 INNER JOIN dbo.x2 ON dbo.x1.type = dbo.x2.type where username = @username ) </code></pre> <p>And so on. The difference is that there is only one row_number() call, with a more complicated ordering expression. All the values will be NULL except for the one actually being used for the sort.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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