【问题标题】:Join strings in Oracle like concat_ws in SQL Server在 Oracle 中加入字符串,如 SQL Server 中的 concat_ws
【发布时间】:2021-10-31 21:00:06
【问题描述】:

我有一个包含多个字符串列的表,我想用分隔符连接在一起。

c1 c2 c3 c4
a b c d
a b
a

结果应该是

'a-b-c-d'
'a-b'
'a'

在 SQL Server 中我只是这样做

select concat_ws('-', c1, c2, c3, c4) from my_table

在 Oracle 中我可以做到

SELECT COALESCE(c1, '') || 
  CASE WHEN c2 IS NULL THEN '' ELSE '-' || c2 END || 
  CASE WHEN c3 IS NULL THEN '' ELSE '-' || c3 END ||
  CASE WHEN c4 IS NULL THEN '' ELSE '-' || c4 END  
FROM my_table

在 Oracle 中是否有更好的解决方案,或者甚至适用于 SQL Server 和 Oracle 的解决方案?

【问题讨论】:

  • 这能回答你的问题吗? Is there an equivalent to concat_ws in oracle?
  • 就两者而言,不幸的是,每种 SQL 方言都可能非常不同。例如,即使是 T-SQL 和 PL/SQL 中的基本连接也完全不同,它们分别使用 +||。如果您使用多种方言,则很少有查询可以在不进行某种最小更改的情况下转移。

标签: sql string oracle concatenation


【解决方案1】:

同时适用于 Oracle 和 SQL Server 的版本很棘手,因为唯一可用的字符串连接函数是带有两个参数的 concat()。但是,你可以这样做:

select trim('-' from
        concat(coalesce(c1, ''),
              concat(case when c2 is null then '' else concat('-', c2) end,
                     concat(case when c3 is null then '' else concat('-', c3) end,
                            case when c4 is null then '' else concat('-', c4) end
                           )
                    )
             ))

这是SQL ServerOracle 的两个dbfiddles。

【讨论】:

    【解决方案2】:

    一种选择是

    • -作为分隔符连接所有列,然后
    • 删除双(三重,...)- 符号(使用正则表达式)和
    • 删除前导/尾随 - 标志(带修剪)

    类似这样的:

    SQL> with test (c1, c2, c3, c4) as
      2    (select 'a' , 'b' , 'c' ,  'd' from dual union all
      3     select 'a' , 'b' , null, null from dual union all
      4     select 'a' , null, null, null from dual union all
      5     select 'a' , null, 'c' , null from dual union all
      6     select null, null, 'c' , 'd'  from dual
      7    )
      8  select
      9    c1, c2, c3, c4,
     10    --
     11    trim(both '-' from regexp_replace(c1 ||'-'|| c2 ||'-'|| c3 ||'-'|| c4, '-+', '-')) result
     12  from test;
    
    C1 C2 C3 C4 RESULT
    -- -- -- -- --------------------
    a  b  c  d  a-b-c-d
    a  b        a-b
    a           a
    a     c     a-c
          c  d  c-d
    
    SQL>
    

    【讨论】:

      【解决方案3】:
      select c1 || nvl2(c2, '-'||c2,c2) || nvl2(c3, '-'||c3,c3) || nvl2(c4, '-'||c4,c4)
      from mytable
      

      测试它here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 2015-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多