SQL Server 2005:以 NULL 值结尾的顺序

问题描述:

可能的重复:
使用 Null 的 Case Order

我希望获得按ordernum"字段排序的记录列表.ordernum 字段是一个 int 字段.此字段从 NULL 开始,直到由用户设置.我希望 NULL 条目出现在列表的末尾.

I'm looking to get a list of records ordered by an "ordernum" field. The ordernum field is an int field. This field starts as NULL until set by a user. I would like the NULL entries to appear at the end of the list.

我正在按如下方式构建查询:

I am building a query as follows:

select *, case when (ordernum is null) then [largestInt] else ordernum end as newordernum
from tableName
order by newordernum

我知道我可以为 [largestInt] 输入最大可能的 int 值,但我想用一个变量替换 [largestInt].这可能吗?

I know I could enter the value for the largest possible int for [largestInt], but I would like to replace [largestInt] with a variable. Is this possible?

我找到了一种在底部对 NULL 值进行排序的方法.

I found a way to order NULL values on the bottom.

http://sqlblog.com/blogs/denis_gobo/archive/2007/10/19/3048.aspx

它很好地满足了我的需求.我的查询现在是:

It meets my needs quite nicely. My query is now:

select *
from tableName
order by case when ordernum is null then 1 else 0 end, ordernum