连接字符串同时满足空值

时间:2018-04-05 09:00:38

标签: sql oracle string-concatenation

我有以下脚本: -

(negate.abs) -7
negate (abs -7)
negate.abs -7

negate.abs $ 7 //only this works

......可能会返回类似的内容: -

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

Oracle是否有可能可靠地连接这些数据,满足空值,并用逗号分隔字符串。因此,上述数据的所需输出为: -

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

2 个答案:

答案 0 :(得分:7)

您可以使用NVL2检查地址组件是否为非空:

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 |

答案 1 :(得分:2)

create function dbo.CheckFunction()
returns int
as begin
    return (select 1)
end

alter table YourTable
add constraint chk_CheckFunction
check (dbo.CheckFunction() = 1)

<强>输出

SELECT siteid,
       REGEXP_REPLACE((address1||','||address2||','||address3||','||address4||','||address5),'[,]+',',') AS address
FROM tblsites

<强>样本

  

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

相关问题