gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:03:55 26 4
gpt4 key购买 nike

我有以下 SQL 查询

select s.comments + s.further_comments from dbo.samples s where id = 1234

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

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

最佳答案

您可以使用 ISNULLCOALESCE为此。

SELECT ISNULL(s.comments, '') + ISNULL(s.further_comments, '')
SELECT COALESCE(s.comments, '') + COALESCE(s.further_comments, '')

ISNULL

Replaces NULL with the specified replacement value.

COALESCE

Returns the first nonnull expression among its arguments.

请注意, some differences在这两种方法之间,但出于所有意图和目的,它们很可能不适用于您的情况。

  1. ISNULL(NULL, NULL) -- is int
  2. COALESCE(NULL, NULL) -- Will throw an error
  3. COALESCE(CAST(NULL as int), NULL) -- it valid and returns int
  4. ISNULL takes only 2 parameters whereas COALESCE takes variable number of parameters
  5. COALESCE is based on the ANSI SQL standard whereas ISNULL is a proprietary TSQL function

关于sql - 在 Sql server 字符串连接中处理 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8063431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com