Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

SQL conditionnel ORDER BY ASC/DESC pour les colonnes alpha

Une possibilité

;WITH cQuery AS
(
   SELECT
       *,
       ROW_NUMBER() OVER (ORDER BY SortColumn) AS RowNum
   FROM
       MyTable
)
SELECT
   *
FROM
   cQuery
ORDER BY
   RowNum * @Direction --1 = ASC or -1 = DESC

Ou CASE qui, à mon humble avis, est un peu plus moche

ORDER BY
  CASE WHEN 'ASC' THEN SortColumn ELSE '' END ASC,
  CASE WHEN 'DESC' THEN SortColumn ELSE '' END DESC