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

时间:2011-02-10 18:09:25

标签: tsql null string-concatenation

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

SELECT City, State, Country,
City + ', ' + State + ', ' + Country AS 'Location'
FROM Users

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

我目前的解决方案是:

SELECT City, State, Country,
City + ', ' + COALESCE(State + ', ', '') + Country AS 'Location'
FROM Users

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

4 个答案:

答案 0 :(得分:14)

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

;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

输出

City State Country Location
---- ----- ------- --------
a    NULL  c       a, c
a    b     c       a, b, c
NULL NULL  c       c

答案 1 :(得分:3)

您可以在SQL 2012及更高版本中使用Concat功能

SELECT City, State, Country,
Concat(City, ', ', State, ', ', Country) AS 'Location'
FROM Users

答案 2 :(得分:2)

是的,这是要走的路。您也可以使用isnull(),但coalesce更标准。您可以考虑在城市或国家/地区是否也有空值。您也可以考虑用户可能拥有多个地址,并且可能有多个城市,州,国家/地区,并且相关的表可能更适合此信息。

答案 3 :(得分:0)

;WITH 

users(City, State, Country) AS (
  SELECT    'a',
            null,
            'c' 
  UNION     ALL
  SELECT    'a',
            'b', 
            'c' 
  UNION     ALL
  SELECT    null,
            null, 
            'c'
)

SELECT      City, 
            State,
            Country,
            CONCAT(City+', ' ,State+', ', Country) AS Location
FROM        Users
相关问题