How to insert a record into multiple tables using

2019-08-01 00:45发布

I have two Tables.

I want to insert the same record on both tables at the same time.
I.e., while I insert a record for the first table, this same record also is inserted in the second table using a trigger.

Do you have any experience/advice in this process ?

3条回答
闹够了就滚
2楼-- · 2019-08-01 00:53

Can Use Cursor Concept!

CREATE OR REPLACE TRIGGER bi_order
BEFORE INSERT
ON ord
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
WHEN (NEW.payment_type = 'CREDIT')
DECLARE
CURSOR cur_check_customer IS
   SELECT 'x'
   FROM   customer
   WHERE  customer_id = :NEW.customer_id
   AND    credit_rating = 'POOR';
lv_temp_txt          VARCHAR2(1);
lv_poor_credit_excep EXCEPTION;
BEGIN
OPEN cur_check_customer;
FETCH cur_check_customer INTO lv_temp_txt;
IF (cur_check_customer%FOUND) THEN
   CLOSE cur_check_customer;
   RAISE lv_poor_credit_excep;
ELSE
   CLOSE cur_check_customer;
END IF;
EXCEPTION
WHEN lv_poor_credit_excep THEN
   RAISE_APPLICATION_ERROR(-20111, 'Cannot process CREDIT ' ||
      'order for a customer with a POOR credit rating.');
WHEN OTHERS THEN
   RAISE_APPLICATION_ERROR(-20122, 'Unhandled error occurred in' ||
      ' BI_ORDER trigger for order#:' || TO_CHAR(:NEW.ORDER_ID));
END bi_order;
查看更多
走好不送
3楼-- · 2019-08-01 01:04

if you're using stored procedures you can easily manage this

CREATE PROCEDURE sp_Insert
@Value varchar(10)
AS
insert into table1 (...,...) values (@value,...)
insert into table2 (...,...) values (@value,...)
查看更多
The star\"
4楼-- · 2019-08-01 01:10

I would suggest using Erik's method over a trigger. Triggers tend to cause performance issues, and a lot of times, you forget that the trigger exists, and get unexpected behavior. If you do want to use a trigger however, it will work. here is an example:

CREATE TRIGGER trgTest ON Test
FOR INSERT
AS
INSERT Test2
     (Id, value)
SELECT Id, Value 
FROM Inserted
查看更多
登录 后发表回答