在Oracle SQL中合并两个字符串

时间:2010-10-02 01:24:30

标签: sql oracle string plsql

有没有办法合并查询中返回的两个字符串,如下所示:我有一个字符串 '<6 spaces>XYZ'和其他字符串'<3 spaces>ABC<3 spaces>'。基本上每个字符串分为3个部分,任何部分中的两个将为空白。我想合并这两个字符串以产生输出:'<3 spaces> ABCXYZ'

另一个示例可以是'ABC<6 spaces>',字符串'<6 spaces>DEF'应该生成'ABC<3 spaces>DEF>'

2 个答案:

答案 0 :(得分:7)

您可以利用空格按字母顺序早于字母和数字的事实:

with q as (select '   ABC   ' as c1,'      DEF' as c2 from dual
 union all select 'ABC      ', '      DEF' from dual
 union all select '   DEF   ', 'ABC      ' from dual
 union all select '      DEF', '   ABC   ' from dual
 union all select 'ABC      ', '   DEF   ' from dual
 union all select '      DEF', 'ABC      ' from dual
)
select c1, c2,
       GREATEST(SUBSTR(c1, 1, 3), SUBSTR(c2, 1, 3)) ||
       GREATEST(SUBSTR(c1, 4, 3), SUBSTR(c2, 4, 3)) ||
       GREATEST(SUBSTR(c1, 7, 3), SUBSTR(c2, 7, 3)) mrg
from q;


C1        C2        MRG       
--------- --------- --------- 
   ABC          DEF    ABCDEF 
ABC             DEF ABC   DEF 
   DEF    ABC       ABCDEF    
      DEF    ABC       ABCDEF 
ABC          DEF    ABCDEF    
      DEF ABC       ABC   DEF 

6 rows selected

答案 1 :(得分:4)

Oracle 10g +:

SELECT t.column1,
       t.column2,
       CASE
         WHEN REGEXP_LIKE(t.column1, '^\w{3}') AND REGEXP_LIKE(t.column2, '\w{3}$') THEN 
           TRIM(t.column1) || '   ' || TRIM(t.column2)            
         WHEN REGEXP_LIKE(t.column1, '^\w{3}') AND REGEXP_LIKE(t.column2, '\s{3}\w{3}') THEN 
           TRIM(t.column1) || TRIM(LEADING FROM t.column2) 
         WHEN REGEXP_LIKE(t.column1, '\s{3}\w{3}') AND REGEXP_LIKE(t.column2, '\w{3}$') THEN 
           TRIM(TRAILING FROM t.column1) || TRIM(t.column2) 
         WHEN REGEXP_LIKE(t.column2, '^\w{3}') AND REGEXP_LIKE(t.column1, '\w{3}$') THEN 
           TRIM(t.column2) || '   ' || TRIM(t.column1)            
         WHEN REGEXP_LIKE(t.column2, '^\w{3}') AND REGEXP_LIKE(t.column1, '\s{3}\w{3}') THEN 
           TRIM(t.column2) || TRIM(LEADING FROM t.column1) 
         WHEN REGEXP_LIKE(t.column2, '\s{3}\w{3}') AND REGEXP_LIKE(t.column1, '\w{3}$') THEN 
           TRIM(TRAILING FROM t.column2) || TRIM(t.column1)   
       END AS col
  FROM table1 t 

支持脚本:

CREATE TABLE "EXAMPLE"."TABLE1" (
  "COLUMN1" VARCHAR2(9 BYTE), 
  "COLUMN2" VARCHAR2(9 BYTE)
);

Insert into TABLE1 (COLUMN1,COLUMN2) values ('   ABC   ','      DEF');
Insert into TABLE1 (COLUMN1,COLUMN2) values ('ABC      ','      DEF');
Insert into TABLE1 (COLUMN1,COLUMN2) values ('   DEF   ','ABC      ');
Insert into TABLE1 (COLUMN1,COLUMN2) values ('      DEF','   ABC   ');
Insert into TABLE1 (COLUMN1,COLUMN2) values ('ABC      ','   DEF   ');
Insert into TABLE1 (COLUMN1,COLUMN2) values ('      DEF','ABC      ');