在Sql server字符串连接中处理NULL

Sim*_*ter 3 sql sql-server string string-concatenation

我有以下SQL查询

select s.comments + s.further_comments from dbo.samples s where id = 1234
Run Code Online (Sandbox Code Playgroud)

但是,如果s.comments或s.further_comments为NULL,则整个字符串返回NULL

如何将NULL值转换为空字符串或至少仅返回此字符串中的非NULL值?

谢谢

Lie*_*ers 6

您可以使用ISNULLCOALESCE.

SELECT ISNULL(s.comments, '') + ISNULL(s.further_comments, '')
SELECT COALESCE(s.comments, '') + COALESCE(s.further_comments, '')
Run Code Online (Sandbox Code Playgroud)

一片空白

Replaces NULL with the specified replacement value.
Run Code Online (Sandbox Code Playgroud)

合并

Returns the first nonnull expression among its arguments.
Run Code Online (Sandbox Code Playgroud)

请注意, 一些差异的两种方法之间但对于所有意图和目的,他们极有可能并不适用于您的情况.

  1. ISNULL(NULL,NULL) - 是int
  2. COALESCE(NULL,NULL) - 将抛出错误
  3. COALESCE(CAST(NULL as int),NULL) - 它有效并返回int
  4. ISNULL只接受2个参数,而COALESCE接受可变数量的参数
  5. COALESCE基于ANSI SQL标准,而ISNULL是专有的TSQL函数