T-SQL:在字符串连接中处理NULL值的最佳方法

Joe*_*ool 10 t-sql null string-concatenation

如果在SELECT语句中我选择了一个使用我正在选择的表中的值的连接字符串,那么处理这些值的NULL的最佳方法是什么,这样我仍然可以使用我的字符串?如同,如果我为用户选择城市,州和国家,我想要第三个字段连接它们:

SELECT City, State, Country,
City + ', ' + State + ', ' + Country AS 'Location'
FROM Users
Run Code Online (Sandbox Code Playgroud)

但是,如果三个字段中的任何一个为NULL,则"位置"为NULL(只要用户不是来自美国,就会发生这种情况).

我目前的解决方案是:

SELECT City, State, Country,
City + ', ' + COALESCE(State + ', ', '') + Country AS 'Location'
FROM Users
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否只是一个黑客,如果有更好的方法来做到这一点.思考?

Ric*_*iwi 17

为了使用每两个字段之间的逗号可以预测正确,您可以使用此表单

;with users(City, State, Country) as (
select 'a', null, 'c' union all
select 'a', 'b', 'c' union all
select null, null, 'c')

-- ignore above this line
SELECT City, State, Country,
    STUFF(
        ISNULL(', ' + City, '')+
        ISNULL(', ' + State, '')+
        ISNULL(', ' + Country, ''), 1, 2, '') AS 'Location'
FROM Users
Run Code Online (Sandbox Code Playgroud)

产量

City State Country Location
---- ----- ------- --------
a    NULL  c       a, c
a    b     c       a, b, c
NULL NULL  c       c
Run Code Online (Sandbox Code Playgroud)

  • @Joe CTE(WITH)子句允许您虚拟定义一个表(或多个),以便在紧随其后的查询(SELECT)中使用.你不需要它,只需在`--ignore`行之后使用查询.我用它来定义SELECT查询的表而不是创建临时表. (3认同)

ced*_*edd 5

您可以在 SQL 2012 及更高版本中使用 Concat 函数

SELECT City, State, Country,
Concat(City, ', ', State, ', ', Country) AS 'Location'
FROM Users
Run Code Online (Sandbox Code Playgroud)