Split varchar into separate columns in Oracle

前端 未结 3 753
难免孤独
难免孤独 2020-12-13 20:10

I\'m in a bit of a pickle: I\'ve been asked to take in comments starting with a specific string from a database, and separate the result into separate columns.

For

相关标签:
3条回答
  • 2020-12-13 20:39

    With REGEXP_SUBSTR is as simple as:

    SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
           REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
    FROM YOUR_TABLE t;
    
    0 讨论(0)
  • 2020-12-13 20:49

    Simple way is to convert into column

    SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))
    
    CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);
    
    CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
       RETURN split_tbl
       PIPELINED IS
       l_idx PLS_INTEGER;
       l_list VARCHAR2 (32767) := p_list;
       l_value VARCHAR2 (32767);
    BEGIN
       LOOP
          l_idx := INSTR (l_list, p_del);
    
          IF l_idx > 0 THEN
             PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
             l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
          ELSE
             PIPE ROW (l_list);
             EXIT;
          END IF;
       END LOOP;
    
       RETURN;
    END split;
    
    0 讨论(0)
  • 2020-12-13 20:59

    Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

    SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
           SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
      FROM YOUR_TABLE t
    

    Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

    Reference:

    • SUBSTR
    • INSTR
    0 讨论(0)
提交回复
热议问题