sql - 奇怪的 SQL 结果

标签 sql tsql

所以我有以下查询

Select id, [First], [Last] , [Business] as contactbusiness, (Case When ([Business] != '' or [Business] is not null) 
        Then [Business] Else 'No Phone Number' END) from contacts

结果是这样的

id  First   Last    contactbusiness (No column name)
2   John    Smith       
3   Sarah   Jane    0411 111 222    0411 111 222
6   John    Smith   0411 111 111    0411 111 111
8                   NULL            No Phone Number
11  Ryan    B       08 9999 9999    08 9999 9999
14  David   F       NULL            No Phone Number

我希望记录 2 也显示无电话号码

如果我将“[Business] is not null”更改为 [Business] != null,那么我会得到正确的结果

id  First   Last    contactbusiness (No column name)
2   John    Smith                   No Phone Number
3   Sarah   Jane    0411 111 222    0411 111 222
6   John    Smith   0411 111 111    0411 111 111
8                   NULL            No Phone Number
11  Ryan    B       08 9999 9999    08 9999 9999
14  David   F       NULL            No Phone Number

通常您需要使用 is not null 而不是 != null。这是怎么回事?

最佳答案

您需要在条件中使用AND,而不是OR:

[Business] != '' and [Business] is not null

这很困惑,因为您使用的是底片。我只是翻转整个条件并使用正数(在这种情况下你会使用 OR):

(Case When ([Business] == '' or [Business] is null) 
    Then 'No Phone Number' Else [Business] END)

关于sql - 奇怪的 SQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964932/

相关文章:

php - 为什么PHP在mysql表数据库中插入变量名

sql - Postgres 使用 UnknownType 值将两个字段合二为一

sql-server - 结果表达式中的 IN 语句 CASE THEN 表达式

sql - 如何从 JSON 字符串读取具有长值的属性?

mysql - 我应该使用连接而不是循环

sql - 如何从 Oracle 中的选定行中获取行号

SQL Management Studio 无法将表/对象从资源管理器拖动到查询编辑器

sql - 在创建 IDENTITY 的同一个 T-SQL 语句中获取 IDENTITY 值?

sql-server - 如何在没有 ON DELETE CASCADE 的情况下进行 DELETE(冲突 REFERENCE 约束)

sql - 在存储过程中出现 if/else 错误