SQL Server排序的時候使null值排在最后


首先建一個表插入一些測試數據

create table UserInfo

     UserInfoID        int not null identity(1,1) primary key,

     User_No          int null,

      User_Names    nvarchar(16)   null

)

insert into UserInfo(User_No,User_Names)

select '104','名稱三' union all

select '103','名稱二' union all

select'108','名稱七' union all

select '105','名稱四'  union all

select'106','名稱五' union all

select '102','名稱一' union all

select '107','名稱六' union all

select'109' ,'名稱八'

insert into UserInfo(User_Names)

select '名稱九' union all

select'名稱十'

select *from UserInfo

下面先直接排序看下效果

select UserInfoID,User_No,User_Names

from UserInfo

order by User_NO asc

可以看到指定排序的列,其值為null的排在了最前面

下面就是解決辦法

select UserInfoID,User_No,User_Names

from UserInfo

order by case when User_NO is null then 1 else 0 end asc,User_NO asc以上就是解決辦法了,既把指定排序列的值為null的排在最后了,也可以按照指定的值進行排序,是不是很簡單


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM