[英]how to split set values and Insert each row in Trigger PL/SQL?
i have one order table. 我有一张订单表。 i need before inserting order table, create and using triggers insert given below format. 我需要在插入订单表之前 ,创建并使用以下格式的触发器插入 。
example: 例:
question: 题:
id value id值
1 2,5,8 1 2,5,8
answer: 回答:
id value id值
1 2 1 2
1 5 1 5
1 8 1 8
Triggers in Oracle have mode "INSTEAD OF" which is exactly what you need, but the problem is that you can't use "INSTEAD OF" trigger on a simple table, it's only available for views. Oracle中的触发器具有“ INSTEAD OF”模式,这正是您所需要的,但是问题是您不能在简单表上使用“ INSTEAD OF”触发器,它仅适用于视图。 So the only option I see for you is to wrap your table in a view. 因此,我为您提供的唯一选择是将表包装在视图中。 For example you have a table: 例如,您有一个表:
create table my_table(c_id number, c_value varchar2(5))
Rename it and create view with old table' name: 重命名它并使用旧表的名称创建视图:
rename my_table to my_table_old;
create view my_table as select * from my_table_old;
All existing queries to my_table should work with this view, including updates and deletes. 所有对my_table的现有查询都应与此视图一起使用,包括更新和删除。 Now we can create INSTEAD OF trigger: 现在我们可以创建INSTEAD OF触发器:
create or replace trigger t_my_table
instead of insert on my_table
for each row
declare
qid number;
begin
insert into my_table_old
select :new.c_id, regexp_substr (:new.c_value, '[^,]+', 1, level) as part
from dual
connect by level <= length (regexp_replace (:new.c_value, '[^,]+')) + 1;
end;
This hierarchial query will turn comma-separated string into a table with single value in a row. 此层次结构查询会将逗号分隔的字符串转换为一行中具有单个值的表。
OK, let's check if it works: 好的,让我们检查一下是否可行:
SQL> insert into my_table values (1, '2,5,8');
1 row created.
SQL> select * from my_table;
C_ID C_VALUE
---------- ---------------
1 2
1 5
1 8
Simple single-value insert will also work: 简单的单值插入也将起作用:
SQL> insert into my_table values (2, '100');
1 row created.
SQL> select * from my_table;
C_ID C_VALUE
---------- ---------------
1 2
1 5
1 8
2 100
Note that using of trigger will affect performance of insert queries for a bit. 请注意,使用触发器会稍微影响插入查询的性能。
You can amend the regex to suit your exact requirements but the following performs effectively as per your question: 您可以修改正则表达式以适合您的确切要求,但以下内容会根据您的问题有效执行:
CREATE OR REPLACE TRIGGER XX_ORDER_TRG
BEFORE INSERT ON XX_ORDER_TBL
FOR EACH ROW
DECLARE
l_num1 NUMBER;
l_num2 NUMBER;
l_num3 NUMBER;
BEGIN
/* If the whole string in value matches 3 single digits separated by commas */
IF REGEXP_LIKE(:new.value,'^(\d{1},\d{1},\d{1})$') THEN
/* Split the value into its 3 separate digits - Capture Groups are not supported natively*/
l_num1 := REGEXP_SUBSTR(:new.value,'\d{1}',1,1);
l_num2 := REGEXP_SUBSTR(:new.value,'\d{1}',1,2);
l_num3 := REGEXP_SUBSTR(:new.value,'\d{1}',1,3);
:new.value := l_num1;
INSERT INTO XX_TBL (id, value) VALUES (:new.id, l_num2);
INSERT INTO XX_TBL (id, value) VALUES (:new.id, l_num3);
END IF;
END;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.