首先对空值进行排序时出错 MSSQL

Error sorting nulls first MSSQL

我的目标是获取 table cat.CAT_RUTAS 中的所有元素,并且我将类型 null 添加到值为 'Enlistar todas las rutas' 的列表中,所以我希望 null 值成为结果的第一个选项,并将其余值按升序排序。

我正在使用 MSSQL SERVER,但是当我尝试 运行 这个查询时:

select CATrut_iIdentificador, CATrut_vDescripcion 
from cat.CAT_Rutas 
UNION 
SELECT NULL , 'Enlistar todas las rutas'
order by CATrut_vDescripcion ASC NULLS FIRST

问题是当我试图将空值添加到顶部时。收到错误:

'NULLS' 附近的语法不正确。

先按这样的 CASE 表达式排序:

ORDER BY 
  CASE WHEN CATrut_iIdentificador IS NULL THEN 0 ELSE 1 END, 
  CATrut_vDescripcion ASC

删除 NULLS FIRST 不存在这样的语法。应该是

select CATrut_iIdentificador, CATrut_vDescripcion 
from cat.CAT_Rutas 
UNION 
SELECT NULL , 'Enlistar todas las rutas'
order by CATrut_vDescripcion

MS SQL 服务器不支持 nulls first 子句。但是,查看 order by clause documentation,您会看到:

Null values are treated as the lowest possible values.

因此,通过 asc 排序,您无需执行任何操作,null 无论如何都会排在第一位:

select CATrut_iIdentificador, CATrut_vDescripcion 
from cat.CAT_Rutas 
UNION 
SELECT NULL , 'Enlistar todas las rutas'
order by CATrut_vDescripcion ASC

这是另一个选项,它只是添加一个新列进行排序。

select CATrut_iIdentificador, CATrut_vDescripcion, 1 as SortOrder
from cat.CAT_Rutas 
UNION 
SELECT NULL , 'Enlistar todas las rutas', 0 as SortOrder
order by SortOrder, CATrut_vDescripcion