Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server dynamic ORDER BY with mixed datatypes: is this a good idea?
    primarykey
    data
    text
    <p>I have stored procedure that returns results sorted dynamically. The parent folder (this is for content management) has a RankTypeID field that allows sorting by Rank (0), Start Date in ascending order (1), Start Date in descending order (2), and document title (3)</p> <p>Rank is an integer, date is smalldatetime, and title is a nvarchar.</p> <p>...</p> <pre><code>ORDER BY Case Parent.RankTypeID When 0 Then dbo.Folders.Rank When 1 Then Cast(dbo.Documents.SortableDateStart As bigint) When 2 Then (1 - Cast(dbo.Documents.SortableDateStart As bigint)) When 3 Then Cast(dbo.Documents.Title as sql_variant) End </code></pre> <p>I set up the SortableDateStart as a computed column to take a DateStart smalldatetime column and convert it into a bigit for sorting. It takes an ISO8601 date (designed for xml usage, and also handy for sorting) and replaces the T, :, and -</p> <pre><code>(replace(replace(replace(CONVERT([varchar](16),[DateStart],(126)),'T',''),'-',''),':','')) </code></pre> <p>This is kind of ugly. Is there a better way to do this? I'm also open to better ways of handling this dynamic sorting.</p> <p><strong>Edit: Test Data Setup</strong></p> <pre><code>DECLARE @Temp TABLE ( [Rank] int, [Title] nvarchar(100), [DateStart] datetime ) INSERT into @Temp SELECT 1, 'title1', '1/1/2010 10:01:00AM' UNION SELECT 2, 'atitle1', '1/1/2010 10:03:00AM' UNION SELECT 3, 'title1', '1/1/2010 10:10:00AM' UNION SELECT 4, 'btitle1', '1/1/2010 10:04:00AM' UNION SELECT 10, 'title1', '1/1/2010 10:07:00AM' UNION SELECT 11, 'dtitle1', '1/1/2010 10:09:00AM' UNION SELECT 12, 'ctitle1', '1/1/2010 10:00:01AM' UNION SELECT 13, 'title1', '1/1/2010 10:10:00AM' DECLARE @RankTypeID tinyint --SET @RankTypeID = 0 -- rank --SET @RankTypeID = 1 -- date start asc SET @RankTypeID = 2 -- date start desc --SET @RankTypeID = 3 -- title SELECT [Rank], [DateStart], [Title] FROM @Temp ORDER BY Case @RankTypeID When 0 Then [Rank] When 1 Then Cast([DateStart] As sql_variant) When 3 Then [Title] else null End, Case @RankTypeID When 2 Then Cast([DateStart] As sql_variant) End DESC </code></pre>
    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.
 

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