You can sort dynamically on many types by introducing a multiplier hack to the Order by
. The implementation will depend on you being able to convert each sortable field to an integer field, like so:
DECLARE @Var1 NVARCHAR(20);
DECLARE @Var2 NVARCHAR(3);
DECLARE @OrderHack INT;
SET @Var1 = 'priority';
SET @Var2 = 'DESC';
IF (@Var2 = 'ASC')
SET @OrderHack = 1;
ELSE
SET @OrderHack = -1;
SELECT *
FROM SortTable
ORDER BY
CASE @var1
WHEN 'priority'
THEN CONVERT(INT, [priority]) * @OrderHack
WHEN 'report_date'
THEN CONVERT(INT, report_date) * @OrderHack
END;
SqlFiddle here
Edit
Just to clarify, as per @t-clausen.dk
's point, the hack is dependent on a a conversion back to a increasing numeric type representing the order. e.g. if you require higher resolution on a DATETIME
to ensure that the time component is also considered in the sort, the INT @OrderHack
can be replaced with a FLOAT
or DECIMAL
etc. Caveat : Using this technique to sort on *CHAR
columns could be challenging, especially if case and accent sensitivity is taken into account.