oracle 存储过程拆分字符串以插入或更新到 table

oracle stored procedure split string for insert or update to a table

嗨,如果我的英语不好,我深表歉意。我是 PL/SQL 的新手,我必须创建一个存储过程来接收以下形式的字符串分隔值:

device_id | table | operation_type | field_1 | field_2| field_n

device_id = Number of a device

table = Table Destiny

operation_type = "I" for insert "U" for update.

field_1 = a field value

field_2 = a field value

field_3 = a field value

field_4 = a field value

字符串的示例可能是这样的:

"555;table_a;I;123;abc;xyz?456;def;uvw?...;...;...;"

; = value colums separator

? = row separator

对于字符串来说,前三个值只出现一次,后面的值是命运中插入或更新的数据table。

如何获取字符串值和 assemble 查询 (insert/update)?

table_a

field_1 | field_2 | field_3 | field_4

123     | abc     | xyz     | 555 

456     | def     | uvw     | 555 

感谢您的帮助,我将不胜感激。

试试这个:

create or replace procedure InsertUpdateValues(cad varchar2) is
data_v DBMS_SQL.VARCHAR2_TABLE;
table_name varchar2(75) := regexp_substr(cad,'[^;]+',instr(cad,';',1,1)); --get table name
operation varchar2(1) := regexp_substr(cad,'[^;]+',instr(cad,';',1,2)); --get operation
id number:=to_number(regexp_substr(cad,'[^;]+',1)); --get id (500) in this case 

begin
select regexp_substr(dat,'[^\?]+',1,level,'i') rows_data bulk collect into data_v  from 
(select regexp_substr(cad,'.*',instr(cad,';',1,3)+1) dat from 
dual)
connect by level <= length (regexp_replace (dat , '[^\?]+'))  +1;

for i in 1..data_v.count loop
    if lower(operation) = 'i' then
        execute immediate 'insert into '||table_name||' values (:f1,:f2,:f3,:f4)'
        using regexp_substr(data_v(i),'[^;]+',1,1),regexp_substr(data_v(i),'[^;]+',1,2),regexp_substr(data_v(i),'[^;]+',1,3),id;

    end if;
    if lower(operation) = 'u' then
        execute immediate 'update '||table_name||' set field_2 = :f2, field_3 = :f3 , field_4 = :f4 where field_1 = :f1' using
        regexp_substr(data_v(i),'[^;]+',1,2),regexp_substr(data_v(i),'[^;]+',1,3),id,regexp_substr(data_v(i),'[^;]+',1,1);

    end if;
end loop;

end;

并这样称呼它:

begin
InsertUpdateValues('555;table_a;I;123;abc;xyz?456;def;uvw');
end;

这将插入 table_a 个值:

field_1 | field_2 | field_3 | field_4

123     | abc     | xyz     | 555 

456     | def     | uvw     | 555