连接字符串同时满足空值

Concatenating Strings whilst catering for nulls

我有以下脚本:-

select
siteid
address1,
address2,
address3,
address4,
address5
from tblsites

...可能会返回类似 :-

的内容
siteid address1     address2 address3   address4   address5
123    1 New Street NULL     New Town   NULL       Newvile
456    2 Elm Road   NULL     NULL       New York   New York

在 Oracle 中是否可以可靠地连接此数据、处理空值并用逗号分隔字符串。因此,上述数据所需的输出是:-

siteid address
123    1 New Street, New Town, Newvile
456    2 Elm Road, New York, New York
SELECT siteid,
       REGEXP_REPLACE((address1||','||address2||','||address3||','||address4||','||address5),'[,]+',',') AS address
FROM tblsites

输出

SITEID  ADDRESS
123     1 New Street,New Town,New vile
456     2 Elm Road,New York,New York

演示

http://sqlfiddle.com/#!4/414cc/13

您可以使用NVL2检查地址组件是否为non-null:

SQL Fiddle

Oracle 11g R2 架构设置:

CREATE TABLE tblsites ( siteid, address1, address2, address3, address4, address5 ) AS
  SELECT 123, '1 New Street', CAST( NULL AS VARCHAR2(50) ), 'New Town', NULL, 'Newvile' FROM DUAL UNION ALL
  SELECT 456, '2 Elm Road', NULL, NULL, 'New York', 'New York' FROM DUAL;

查询 1:

SELECT siteid,
       RTRIM(
            NVL2( address1, address1 || ', ', NULL )
         || NVL2( address2, address2 || ', ', NULL )
         || NVL2( address3, address3 || ', ', NULL )
         || NVL2( address4, address4 || ', ', NULL )
         || NVL2( address5, address5 || ', ', NULL ),
         ', '
       ) AS address
FROM   tblsites

Results:

| SITEID |                         ADDRESS |
|--------|---------------------------------|
|    123 | 1 New Street, New Town, Newvile |
|    456 |  2 Elm Road, New York, New York |