如果我的英语不好,我很抱歉。我是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
对于字符串,前三个值仅出现一次,接下来的值是destiny表中插入或更新的数据。
如何获取字符串值并组装查询(插入/更新)?
table_a
field_1 | field_2 | field_3 | field_4
123 | abc | xyz | 555
456 | def | uvw | 555
感谢您的帮助,我真的很感激。
答案 0 :(得分:0)
试试这个:
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