简体   繁体   English

SQL case 0 然后 NULL

[英]SQL case 0 then NULL

I wanna get NULL when the number in my table is 0. Can I achieve this using SQL?当我的表中的数字为 0 时,我想获得 NULL。我可以使用 SQL 来实现吗?

SELECT ID, 
       Firstname, 
       Lastname, 
       CASE Number 
         WHEN 0 THEN NULL 
       END
  FROM tPerson

Error:错误:

At least one of the result expressions in a CASE specification must be an expression other than the NULL constant. CASE 规范中的至少一个结果表达式必须是 NULL 常量以外的表达式。

Thanks in advance!提前致谢!

As others have mentioned you forgot to tell your CASE statement to return the number in case the number is not null.正如其他人提到的,您忘记告诉您的 CASE 语句返回数字,以防数字不为空。

However in SQL Server you can use NULLIF, which I consider more readable:但是在 SQL Server 中,您可以使用 NULLIF,我认为它更具可读性:

select 
  id, 
  firstname, 
  lastname, 
  nullif(number, 0) as number
from tperson;

If you want to stick to standard SQL then stay with CASE:如果您想坚持使用标准 SQL,请继续使用 CASE:

case when number = 0 then null else number end as number

May be you need ELSE :可能你需要ELSE

SELECT 
  ID, Firstname, Lastname CASE Number WHEN 0 THEN NULL ELSE Number END
FROM tPerson
SELECT ID, Firstname, Lastname,
 CASE WHEN Number!=0 THEN Number END 
FROM tPerson

You can simply use IIF() with sql server 2012 and above您可以简单地将 IIF() 与 sql server 2012 及更高版本一起使用

SELECT ID, 
       Firstname, 
       Lastname, 
       IIF(Number = 0, NULL, Number) as Number 
       END
FROM tPerson

Try:尝试:

SELECT ID, Firstname, 
   Lastname, 
   CASE Number WHEN 0 THEN NULL ELSE Number END 
FROM tPerson

在 MySQL 中,您还可以使用if

select if(number = 0, null, number) ... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM