将列连接到单个列的更好方法

时间:2014-05-02 08:14:59

标签: sql-server tsql sql-server-2012

请考虑下表,其中包含人员的地址详细信息:

DECLARE @tbl TABLE
    (
    userId int IDENTITY(1,1),
    address1 nvarchar(100),
    address2 nvarchar(100),
    address3 nvarchar(100),
    addressTown nvarchar(100),
    addressCounty nvarchar(100),
    addressPostCode nvarchar(10)
    );
INSERT INTO 
    @tbl (address1, address2, address3, addressTown, addressCounty, addressPostCode) 
VALUES 
    ('1 Some Road', 'High Hill', 'Battersea', 'London', NULL, 'SW1 2AB'),
    ('54 Main Street', 'Lowville', NULL, 'Sometown', 'Cumbria', 'AB12 3BA');

SELECT * FROM @tbl;

输出显示:

userId      address1        address2       address3      addressTown      addressCounty  addressPostCode
----------- --------------- -------------- ------------- ---------------- -------------  ---------------
1           1 Some Road     High Hill      Battersea     London           NULL           SW1 2AB
2           54 Main Street  Lowville       NULL          Sometown         Cumbria        AB12 3BA

但是,出于此语句的目的,我想将所有地址字段连接到一个字段中,以便结果如下所示:

userId      Address
----------- --------------------
1           1 Some Road
            High Hill
            Battersea
            London
            SW1 2AB
2           54 Main Street
            Lowville
            Sometown
            Cumbria
            AB12 3BA

请注意,这与在单个列中连接行(使用XML等)的问题不同!

我使用以下方法完成了这项工作,但对于这么小的任务来说,似乎有很多代码:

SELECT
    userId,
    CASE WHEN address1 IS NOT NULL THEN
        address1 + CHAR(13) + CHAR(10)
        ELSE ''
    END +
    CASE WHEN address2 IS NOT NULL THEN
        address2 + CHAR(13) + CHAR(10)
        ELSE ''
    END +
    CASE WHEN address3 IS NOT NULL THEN
        address3 + CHAR(13) + CHAR(10)
        ELSE ''
    END +
    CASE WHEN addressTown IS NOT NULL THEN
        addressTown + CHAR(13) + CHAR(10)
        ELSE ''
    END +
    CASE WHEN addressCounty IS NOT NULL THEN
        addressCounty + CHAR(13) + CHAR(10)
        ELSE ''
    END  +
    CASE WHEN addressPostCode IS NOT NULL THEN
        addressPostCode + CHAR(13) + CHAR(10)
        ELSE ''
    END as [Address]
FROM
    @tbl

是否有更好/更快/更推荐的方法来实现这一目标?

2 个答案:

答案 0 :(得分:1)

如果您愿意,可以使用ISNULL(或COALESCE

 select
      ISNULL(Address1 + char(13) + char(10), '') +
      ISNULL(Address2 + char(13) + char(10), '') + ...
 from @tbl

(因为NULL +某些东西仍为NULL)

答案 1 :(得分:0)

感谢@ podiluska的输入,这里是最后的答案,如果整个连接的地址仍为NULL,也可以确保返回NULL:

SELECT
    userId,
    NULLIF(ISNULL(address1 + CHAR(13) + CHAR(10), '') +
            ISNULL(address2 + CHAR(13) + CHAR(10), '') +
            ISNULL(address3 + CHAR(13) + CHAR(10), '') +
            ISNULL(addressTown + CHAR(13) + CHAR(10), '') +
            ISNULL(addressCounty + CHAR(13) + CHAR(10), '') +
            ISNULL(addressPostCode + CHAR(13) + CHAR(10), ''), '') as [Address]
FROM
    @tbl;