在oracle sql中格式化字符串

6psbrbz9  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(504)

我正在尝试获取一个varchar2,它是过程的输入并格式化它,然后用新字符串进行一些计算。输入将是一系列逗号分隔的名称:
例如:姓名、id、地址
我需要的是找到一种方法将上述内容更改为:

CAST(name AS VARCHAR2(200)) name, 
CAST(id AS VARCHAR2(200)) id, 
CAST(address AS VARCHAR2(200)) address

我试着看着 REGEXP_REPLACE 但我是一个初学者,所以我不知道如何正确使用正则表达式。
(顺便说一下,这是针对oracle sql的)

aor9mmx1

aor9mmx11#

你并不真的需要正则表达式; instr + substr 把工作做好,因为它很简单。

SQL> create or replace procedure p_test (par_string in varchar2) is
  2    -- comma positions
  3    l_pos1    number := instr(par_string, ',', 1, 1);
  4    l_pos2    number := instr(par_string, ',', 1, 2);
  5    l_pos3    number := instr(par_string, ',', 1, 3);
  6    -- variables
  7    l_name    varchar2(200);
  8    l_id      varchar2(200);
  9    l_address varchar2(200);
 10  begin
 11    l_name    := substr(par_string, 1, l_pos1 - 1);
 12    l_id      := substr(par_string, l_pos1 + 1, l_pos2 - l_pos1 - 1);
 13    l_address := substr(par_string, l_pos2 + 1);
 14
 15    dbms_output.put_line('Name    = ' || l_name);
 16    dbms_output.put_line('ID      = ' || l_id);
 17    dbms_output.put_line('Address = ' || l_address);
 18  end;
 19  /

Procedure created.

测试:

SQL> set serveroutput on
SQL> exec p_test('Little Foot,25,Manhattan 23 New York');
Name    = Little Foot
ID      = 25
Address = Manhattan 23 New York

PL/SQL procedure successfully completed.

SQL>
u0njafvf

u0njafvf2#

看起来这个应该适合你:

create or replace procedure p_test(params in varchar2) as 
   -- type for string array (collection/nested table)
   type t_str_array is table of varchar2(100);
   -- string array
   str_array t_str_array:=t_str_array();
   -- variable for a count of elements in comma-separated list
   cnt int;

   name    varchar2(100);
   id      varchar2(100);
   address varchar2(100);
begin
   -- count of elements in comma-separated list:
   cnt := regexp_count(params,'[^,]+');
   -- extending string collection up to CNT elements:
   str_array.extend(cnt);
   -- iterate and fill array:
   for i in 1..cnt loop
      str_array(i):=regexp_substr(params,'[^,]+',1,i);
   end loop;

   -- now we can set required variables to the values from array by their positions:
   name   :=str_array(1);
   id     :=str_array(2);
   address:=str_array(3);

   -- print them to check anddebug:
   dbms_output.put_line(utl_lms.format_message('name = %s, id = %s, addr = %s', name, id, address));
end;
/

测试和测试:

SQL> call p_test('Pups,1,Interstate 60');
name = Pups, id = 1, addr = Interstate 60

Call completed.
3wabscal

3wabscal3#

我正在写select语句,它的表达式由substr和instr组成。也可以在过程中使用相同的表达式来获得所需的输出。我假设示例字符串包含逗号分隔的name、id、address值。

SELECT SUBSTR(example_string,1,INSTR(example_String,',',1,1)-1) AS name, SUBSTR(example_string,INSTR(example_String,',',1,1)+1,INSTR(example_String,',',1,2)-INSTR(example_String,',',1,1)-1) AS id, SUBSTR(example_string,INSTR(example_String,',',1,2)+1) AS address FROM dual;

相关问题