仅在SQL Server中不为null的情况下如何串联? [英] How do I concatenate only if not null in SQL Server?

查看:85
本文介绍了仅在SQL Server中不为null的情况下如何串联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这张桌子:

PersonTable

PersonTable

|  id  | name |
---------------
|  10  | Mike |
| NULL | Jane |

我想从表中选择ID和名称,并在ID上使用concat,但前提是它不为null,像这样:

I want to select id and name from the table and use concat on id, but only if it's not null, like this:

+------+------+
|  Id  | Name |
+------+------+
| A10  | Mike |
| NULL | Jane |
+------+------+

我尝试了以下操作:

SELECT ISNULL(concat('A', id), NULL) AS id, name FROM PeronTable

但是我的查询返回以下内容:

But my query returns this:

+-----+------+
| Id  | Name |
+-----+------+
| A10 | Mike |
| A   | Jane |
+-----+------+


推荐答案

嗯。您可以使用 + 代替 concat()

select 'A' + convert(varchar(255), id), name
from t;

convert()(或 cast ())是必需的,假设 id 是数字而不是字符串。

convert() (or cast()) is necessary assuming that id is a number and not a string.

+ 如果任何参数为 NULL 则返回 NULL ; concat()忽略 NULL 自变量。

+ returns NULL if any argument is NULL; concat() ignores NULL arguments.

当然,您可以使用 concat() case 表达式:

Of course, you can use concat() with a case expression:

select (case when id is not null then concat('A', id) end), name
from t;

这篇关于仅在SQL Server中不为null的情况下如何串联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆