简体   繁体   English

具有多个THEN子句的SQL Server CASE语句

[英]SQL Server CASE statement with multiple THEN clauses

I have seen several similar questions but none cover what I need. 我见过几个类似的问题,但没有一个满足我的需求。 I need to put another THEN statement after the first one. 我需要在第一个之后添加另一个THEN语句。 My column contains int's. 我的专栏包含int。 When it returns NULL I need it to display a blank space, but when I try the below code, I just get '0'. 当它返回NULL时,我需要它显示一个空格,但是当我尝试下面的代码时,我只会得到'0'。

CASE 
    WHEN Column1 IS NULL  
    THEN ''
    ELSE Column1
END

If I try to put a sting after THEN then it tells me that it cannot convert it from int. 如果我尝试在“ THEN”后面加上一个小号,则它告诉我它不能将其从int转换。 I need to convert it to varchar and then change its output to a blank space afterwards, such as: 我需要将其转换为varchar,然后将其输出更改为空白,例如:

eg 例如

CASE 
    WHEN Column1 IS NULL 
    THEN CONVERT(varchar(10), Column1)
    THEN ''
    ELSE Column1
END

Is there a way of doing this? 有办法吗?

Thanks Rob 谢谢罗布

A case expression returns a single value -- with a given type. case表达式返回单个值-具有给定类型。 If you want a string result, then you need to be sure that all paths in the case return strings: 如果需要字符串结果,则需要确保case中的所有路径都返回字符串:

CASE WHEN Column1 IS NULL  
     THEN ''
     ELSE CAST(Column1 AS VARCHAR(255))
END

This is more simply written using COALESCE() : 这更简单地使用COALESCE()编写:

COALESCE(CAST(Column1 as VARCHAR(255)), '')

You cannot display an integer as a "blank" (other than using a NULL value). 您不能将整数显示为“空白”(使用NULL值除外)。

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

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