检查 CASE 语句中的空日期,我哪里出错了?
我的源表看起来像这样
Id StartDate
1 (null)
2 12/12/2009
3 10/10/2009
我想创建一个选择语句,选择上面的内容,但还有一个附加列来显示 varchar 如果日期不为空,例如:
Id StartDate StartDateStatus
1 (null) Awaiting
2 12/12/2009 Approved
3 10/10/2009 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 是一个“小日期时间”,是否存在一些例外情况得到治疗?
谢谢
My source table looks like this
Id StartDate
1 (null)
2 12/12/2009
3 10/10/2009
I want to create a select statement, that selects the above, but also has an additional column to display a varchar if the date is not null such as :
Id StartDate StartDateStatus
1 (null) Awaiting
2 12/12/2009 Approved
3 10/10/2009 Approved
I have the following in my select, but it doesn't seem to be working. All of the statuses are set to Approved
even though the dates have some nulls
select
id,
StartDate,
CASE StartDate
WHEN null THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
The results of my query look like :
Id StartDate StartDateStatus
1 (null) Approved
2 12/12/2009 Approved
3 10/10/2009 Approved
4 (null) Approved
5 (null) Approved
StartDate is a smalldatetime
, is there some exception to how this should be treated?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
我认为,您的代码会执行 When StartDate = NULL 。
NULL
永远不等于NULL
(因为 NULL 表示没有值)。NULL
也永远不等于NULL
。上述语法是 ANSI SQL 标准,反之则为StartDate IS NOT NULL
。您可以运行以下命令:
这将返回:
为了完整起见,在 SQL Server 中您可以:
这将导致您的 equals 比较以不同的方式工作:
哪个返回:
但我强烈建议不要这样做。随后维护您的代码的人员可能会被迫追捕您并伤害您...
此外,它将不再在即将推出的 SQL Server 版本中工作:
https://msdn.microsoft.com/en-GB/library/ms188048.aspx
Try:
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal toNULL
(as NULL is the absence of a value).NULL
is also never not equal toNULL
. The syntax noted above is ANSI SQL standard and the converse would beStartDate IS NOT NULL
.You can run the following:
And this returns:
For completeness, in SQL Server you can:
Which would result in your equals comparisons working differently:
Which returns:
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
https://msdn.microsoft.com/en-GB/library/ms188048.aspx