我的源表看起来像这样
Id StartDate
1 (null)
2 12/12/2009
3 10/10/2009
我想创建一个选择上面的select语句,但是如果日期不为null,还有一个额外的列来显示varchar,如:
Id StartDate StartDateStatus
1 (null) Awaiting
2 12/12/2009 Approved
3 10/10/2009 Approved
我的选择中有以下内容,但似乎没有效果。即使日期有一些空值,所有状态都设置为Approved
select
id,
StartDate,
CASE StartDate
WHEN null THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
我的查询结果如下:
Id StartDate StartDateStatus
1 (null) Approved
2 12/12/2009 Approved
3 10/10/2009 Approved
4 (null) Approved
5 (null) Approved
StartDate是smalldatetime
,对于应该如何处理它有一些例外吗?
由于
答案 0 :(得分:68)
尝试:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
我认为,你的代码一直在做一个StartDate = NULL。
NULL
永远不会等于NULL
(因为NULL是缺少值)。 NULL
也永远不等于NULL
。上面提到的语法是ANSI SQL标准,反之亦然是StartDate IS NOT NULL
。
您可以运行以下命令:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
然后返回:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
为了完整起见,在SQL Server中您可以:
SET ANSI_NULLS OFF;
这将导致您的平等比较工作方式不同:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
返回:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
但我强烈建议不要这样做。人们随后维护你的代码可能会被迫追捕并伤害你......
此外,它将不再适用于即将推出的SQL Server版本:
答案 1 :(得分:3)
select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
'Awaiting'
Else
'Approved'
END AS StartDateStatus
From MyTable