我有一个包含管道分隔值的列,例如:
'23 | 12.1 | 450 | 30 | 9 | 78 | 82.5 | 92.1 | 120 | 185 | 52 | 11'
我想解析此列以填充包含12个相应列的表:month1,month2,month3 ... month12。
因此month1将具有值23,month2将具有值12.1等...
有没有办法通过循环或分隔符解析它,而不必使用substr一次分隔一个值?
感谢。
答案 0 :(得分:9)
您可以使用regexp_substr
(10g +):
SQL> SELECT regexp_substr('23|12.1| 450|30|9|', '[^|]+', 1, 1) c1,
2 regexp_substr('23|12.1| 450|30|9|', '[^|]+', 1, 2) c2,
3 regexp_substr('23|12.1| 450|30|9|', '[^|]+', 1, 3) c3
4 FROM dual;
C1 C2 C3
-- ---- ----
23 12.1 450
使用PL / SQL中的循环:
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
2 p_tsv VARCHAR2(1000) := '23|12.1| 450|30|9|78|82.5|92.1|120|185|52|11';
3 l_item VARCHAR2(100);
4 BEGIN
5 FOR i IN 1 .. length(p_tsv) - length(REPLACE(p_tsv, '|', '')) + 1 LOOP
6 l_item := regexp_substr(p_tsv, '[^|]+', 1, i);
7 dbms_output.put_line(l_item);
8 END LOOP;
9 END;
10 /
23
12.1
450
30
9
78
82.5
92.1
120
185
52
11
PL/SQL procedure successfully completed
你只有有12列,我会直接写一个没有循环的查询,它比动态SQL更高效,更容易维护(更不用说写起来更容易了):
INSERT INTO your_table
(ID, month1, month2, month3...)
SELECT :p_id,
regexp_substr(:p_tsv, '[^|]+', 1, 1) c1,
regexp_substr(:p_tsv, '[^|]+', 1, 2) c2,
regexp_substr(:p_tsv, '[^|]+', 1, 3) c3
...
FROM dual;
答案 1 :(得分:0)
答案 2 :(得分:0)
我有99个问题 所以我用了正则表达式 现在我有100个问题 hahahahahahaha 只需将delim连接到开头和&字符串结尾
纯sql解决方案:
set define on
undefine string
undefine delim
undefine nth
accept string prompt 'Enter the string: '
accept delim prompt 'Enter the delimiter: '
accept nth prompt 'Enter nth: '
select '&&string' as string,
'&&delim' as delimiter,
&&nth||decode(&&nth,1,'st',2,'nd',3,'rd','th') as nth,
substr('&&delim'||'&&string'||'&delim',
instr('&&delim'||'&&string'||'&&delim', '&&delim', 1, &&nth ) + length('&&delim'),
instr('&&delim'||'&&string'||'&&delim', '&&delim', 1, &&nth + 1 ) - instr('&&delim'||'&&string'||'&&delim', '&&delim', 1, &&nth ) - length('&&delim')
) as val from dual
/