Oracle APEX - AFTER INSERT, UPDATE another table trigger - sql

I'm trying to insert into the poPayment table with some of the details from the purchaseOrder table AFTER INSERT ON purchaseorder, to start with I want the
purchaseorder.purchaseorderid added into the popayment.purchaseorderid
after I get this working I want to expand the trigger
here is the purchase order table;
CREATE TABLE purchaseOrder
(
purchaseOrderid NUMBER (6) NOT NULL,
staffid NUMBER (6),
rawMaterialid2 NUMBER (6) NOT NULL,
supplierContactid2 NUMBER (6),
orderDate DATE NOT NULL,
dueDate DATE,
pricePerUnit NUMBER (7,2),
qty NUMBER,
total NUMBER (7,2),
CONSTRAINT purchaseOrderid PRIMARY KEY(purchaseOrderid)
);
here is the purchase order payment table;
CREATE TABLE poPayment
(
poPaymentid NUMBER (6) NOT NULL,
purchaseOrderid NUMBER (6) NOT NULL,
staffid NUMBER (6) NOT NULL,
paymentDate DATE,
amountPaid NUMBER (7,2),
qtyOrdered NUMBER (6),
qtyDelievered NUMBER (6),
invoiceAmount NUMBER (6),
dateDelivered DATE,
CONSTRAINT pk_poPaymentid PRIMARY KEY(poPaymentid)
);
and here is the trigger I tried
CREATE OR REPLACE TRIGGER createPOpayment_trg
ON purchaseorder
AFTER INSERT
AS BEGIN
INSERT INTO popayment (purchaseorderid)
SELECT
purchaseorder.purchaseorderid
FROM purchaseorder
WHERE purchaseorder.purchaseorderid = popayment.purchaseorderid
END
Thank
Brian

You have incorrect syntax for the create trigger statement; the AFTER INSERT' needs to be before theON purchaseorder` part (the dml_event_clause in the syntax diagrams). You also want it to be a row-level trigger, so it fires for each individual row you insert in the table;
CREATE OR REPLACE TRIGGER createPOpayment_trg
AFTER INSERT
ON purchaseorder
FOR EACH ROW
AS
...
But then your current insert is malformed too. It's going to insert a row into popayment for every row in purchaseorder that already has a matching popayment row - which is going to duplicate all existing rows, not create one for your new purchase order.
You only want to insert a single row matching the inserted purchase order. And you need to include at least all the not null columns:
BEGIN
INSERT INTO popayment (poPaymentid, purchaseorderid, staffid)
VALUES (popayment_seq.nextval, :new.purchaseorderid, :new.staffid);
END;
I'm guessing (and hoping) you have a sequence to populate the poPaymentid primary key. The other two values are coming from the inserted purchaseorder record, using the :new pseudorecord. You do not want to query the table you are inserting into.
If the key is being set by its own trigger then you only need to give the other two not-null columns (plus any more you add later):
BEGIN
INSERT INTO popayment (purchaseorderid, staffid)
VALUES (:new.purchaseorderid, :new.staffid);
END;

Related

sql oracle - constraint on 2 columns from different tables

I have designed a ticket system booking for flights. I want to add a constraint such that the number of tickets you can insert to be less than number of seats from a flight plane.
Let's say I inserted a flight with a plane with 10 seats. I can insert only 10 tickets for that particular flight. Otherwise, an error message should appear.
I tried to make a trigger using the count function on flight number.
CREATE OR REPLACE TRIGGER trg_ticket_BRIU
BEFORE INSERT OR UPDATE ON Ticket
FOR EACH ROW
DECLARE
l_numberofseats flight.numberofseats%type;
BEGIN
select numberofseats into l_numberofseats
from flight
where flightnumber=:new.flightnumber;
IF :new.count(flightnumber) > l_numberofseats
THEN
raise_application_error(-2000, 'Not enough seats');
END IF;
END;
but I get this error
Trigger TRG_TICKET_BRIU compiled
LINE/COL ERROR
--------- -------------------------------------------------------------
8/5 PLS-00049: bad bind variable 'NEW.COUNT'
Errors: check compiler log
Personally, I would add an AIRCRAFT and a SEAT table:
CREATE TABLE aircraft (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT aircraft__id__pk PRIMARY KEY,
tail_number VARCHAR2(6)
NOT NULL
CONSTRAINT aircraft__tn__u UNIQUE
CONSTRAINT aircraft__tn_chk CHECK(
REGEXP_LIKE(
tail_number,
'[A-Z]\d{1,5}|[A-Z]\d{1,4}[A-Z]|[A-Z]\d{1,3}[A-Z]{2}'
)
),
manufacturer VARCHAR2(20)
NOT NULL,
model VARCHAR2(20)
NOT NULL,
airline_id CONSTRAINT aircraft__aid__fk REFERENCES airline(airline_id)
NOT NULL
);
CREATE TABLE seat (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT seat__id__pk PRIMARY KEY,
aircraft_id CONSTRAINT seat__aid__fk REFERENCES aircraft(id)
NOT NULL,
seat_row VARCHAR2(3)
NOT NULL,
seat_column NUMBER
NOT NULL,
CONSTRAINT seat__aid_r_c__u UNIQUE (aircraft_id, seat_row, seat_column)
);
Then your flight table would reference the aircraft:
CREATE TABLE flight (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT flight__id__pk PRIMARY KEY,
aircraft_id CONSTRAINT flight__aid__fk REFERENCES aircraft(id)
NOT NULL
-- ...
);
And the ticket would reference a flight and a seat:
CREATE TABLE ticket (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT ticket__id__pk PRIMARY KEY,
flight_id CONSTRAINT ticket__fid__fk REFERENCES flight(id)
NOT NULL,
seat_id CONSTRAINT ticket__sid__fk REFERENCES seat(id)
NOT NULL,
-- ...
CONSTRAINT ticket__fid_sid__u UNIQUE (flight_id, seat_id)
);
Then you can never sell a seat that does not exist on an aircraft and do not need to count the maximum number of tickets and compare it to seats (and the seat has added attributes like its location on the plane that can be displayed on the ticket).
All you need then is to ensure the referential consistency that, for a ticket, the flight and the seat are on the same aircraft; which can be done with a trigger:
CREATE TRIGGER ticket_check_seat_on_flight
BEFORE INSERT OR UPDATE ON ticket
FOR EACH ROW
DECLARE
is_valid NUMBER(1);
BEGIN
SELECT 1
INTO is_valid
FROM flight f
INNER JOIN seat s
ON (f.aircraft_id = s.aircraft_id)
WHERE f.id = :NEW.flight_id
AND s.id = :NEW.seat_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(
-20000,
'Flight and seat are on different aircraft.'
);
END;
/
db<>fiddle here
You can use an AFTER STATEMENT trigger:
CREATE TRIGGER ticket__check_number_of_seats
AFTER INSERT OR UPDATE OR DELETE ON ticket
DECLARE
is_invalid NUMBER(1,0);
BEGIN
SELECT 1
INTO is_invalid
FROM flight f
INNER JOIN (
SELECT flight_id,
COUNT(*) AS tickets_sold
FROM ticket
GROUP BY flight_id
) t
ON f.id = t.flight_id
WHERE t.tickets_sold > f.number_of_seats;
RAISE_APPLICATION_ERROR(
-20000,
'Too many tickets sold for flight.'
);
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
/
It could be made more efficient by using a compound trigger to collate, for each row, the flight_id values into a collection and then, after the statement, only checking the number of tickets for those flights; however, I'll leave that extension as an exercise for the OP.
db<>fiddle here
As others indicated there is no :new.count column. This is because :new (and :old) create a pseudo-row containing exactly the same columns as the table definition. Further you will get a Mutating exception as what you need to count in the flight_number from tickets. However, since that is the table causing he trigger to fire you cannot reference it. So what to do: create a compound trigger, and a supporting Type (nested table). Within it use the after row section to capture the flight_numbers processed. Then in the after statement section you can select count of tickets for each flight. If that count > 0 then raise your exception. ( see Demo )
create type flight_tickets_ntt
is table of integer;
create or replace trigger trg_ticket_ciu
for update or insert on tickets
compound trigger
l_flights flight_tickets_ntt := flight_tickets_ntt();
after each row is
begin
if :new.flight_number not member of l_flights then
l_flights.extend ;
l_flights(l_flights.count) := :new.flight_number;
end if;
end after each row;
after statement is
l_flight_cnt flight.flight_number%type;
begin
select count(*)
into l_flight_cnt
from flight f
where f.number_of_seats <
( select count(*)
from tickets t
where t.flight_number in
( select *
from table (l_flights)
)
);
if l_flight_cnt > 0 then
raise_application_error(-20000, 'Not enough seats');
end if;
end after statement;
end trg_ticket_ciu;
There remains a you need to handle: What happens if an update changes the flight number or perhaps (missing column) the data of the flight.

Trigger after insert to check and compare records between table

In an Oracle Database, I need to create some trigger or procedure to treat this case in the most performative way possible (is an extremely large amount of data).
I have a table called ORDER_A that every day receives a full load (its truncated, and all records are inserted again).
I have a table called ORDER_B which is a copy of ORDER_A, containing the same data and some additional control dates.
Each insertion on ORDER_A must trigger a process that looks for a record with the same identifier (primary key: order_id) in table B.
If a record exists with the same order_id, and any of the other columns have changed, an update must be performed on table B
If a record exists with the same order_id, and no values ​​in the other columns have been modified, nothing should be performed, the record must remain the same in table B.
If there is no record with the same order_id, it must be inserted in table B.
My tables are like this
CREATE TABLE ORDER_A
(
ORDER_ID NUMBER NOT NULL,
ORDER_CODE VARCHAR2(50),
ORDER_STATUS VARCHAR2(20),
ORDER_USER_ID NUMBER,
ORDER_DATE TIMESTAMP(6),
PRIMARY KEY (ORDER_ID)
);
CREATE TABLE ORDER_B
(
ORDER_ID NUMBER NOT NULL,
ORDER_CODE VARCHAR2(50),
ORDER_STATUS VARCHAR2(20),
ORDER_USER_ID NUMBER,
ORDER_DATE TIMESTAMP(6)
INSERT_AT TIMESTAMP(6),
UPDATED_AT TIMESTAMP(6),
PRIMARY KEY (ORDER_ID)
);
I have no idea how to do this and what is the best way (with a trigger, procedure, using merge, etc.)
Can someone give me a direction, please?
Here is some pseudo-code to show you a potential trigger based solution that does not fall back into slow row-by-row processing.
create or replace trigger mytrg
for insert or update delete on ordera
compound trigger
pklist sys.odcinumberlist;
before statement is
begin
pklist := sys.odcinumberlist();
end before statement ;
after each row is
begin
pklist.extend;
pklist(pklist.count) := :new.order_id;
end before each row;
after statement is
begin
merge into orderb b
using (
select a.*
from ordera a,
table(pklist) t
where a.order_id = t.column_value
) m
when matched then
update
set b.order_code = m.order_code,
b.order_status = m.order_status,
...
where decode(b.order_code,m.order_code,0,1)=1
or decode(b.order_status,m.order_status,0,1)=1
....
when not matched then
insert (b.order_id,b.order_code,....)
values (m.order_id,m.order_code,....);
end after statement ;
end;
We hold the impacted primary keys, and then build a single merge later, with an WHERE embed to minimise update activities.
If your application allows the update of primary keys, you'd need some additions, but this should get you started

How to insert multiple values in one column of type number in oracle?

I have table like
CREATE TABLE TEMP_TABLE
(
temp_acct number(10) NOT NULL,
temp_code varchar2(250),
temp_bal number(10,2),
CONSTRAINT TEMP_TABLE_PK PRIMARY KEY(temp_acct)
);
Is it possible to insert multiple values into column temp_bal in one row something like below,I know the syntax is incorrect but is there any way?
INTO TEMP_TABLE (temp_acct, temp_code, temp_bal)
VALUES (1000, 'code100, code101, code102, code103', '1000.00,2000.00,3000.00');

Use a Trigger After Insert for updating a table?

I'm using a Trigger on SQL server to update a table stock when a sell is inserted into another table, but the trigger is not doing anything to the table, I suspect I must have an error I can't decipher. When I execute the test Inserts it shows no change to the first table.
The tables are:
Sku VARCHAR (50) PRIMARY KEY,
Stock NUMERIC (38)
);
CREATE TABLE dbo.Salida_Producto (
Numero_Salida INT PRIMARY KEY,
Sku VARCHAR (50),
Cantidad_Salida INT,
FOREIGN KEY(Sku) REFERENCES Stock(Sku)
);
--Test Tabla Stock. Test Values.
INSERT INTO dbo.Stock VALUES ('El Mitchies',100);
INSERT INTO dbo.Stock VALUES ('La Karencilla',200);
INSERT INTO dbo.Stock VALUES ('Perro',300);```
The Trigger:
CREATE TRIGGER [dbo].[tr_for_insert]
ON [dbo].[Salida_Producto]
AFTER INSERT
AS
BEGIN
DECLARE
#Item varchar,
#Cuantos numeric
SELECT #Item = INSERTED.Sku,
#Cuantos = INSERTED.Cantidad_Salida
FROM INSERTED
UPDATE Stock
SET Stock = Stock - #Cuantos
WHERE Sku = #Item
END;
GO
Test Inserts
INSERT INTO dbo.Salida_Producto VALUES (1, 'El Mitchies',3);
INSERT INTO dbo.Salida_Producto VALUES (2, 'La Karencilla',6);
INSERT INTO dbo.Salida_Producto VALUES (3,'Perro',130); ```
The problem I have is that the message box says:
(0 row(s) affected)
(1 row(s) affected)
You have thought your trigger with a row by row approach. It is not good practice. You must learn to think with a "by set" approach.
So a better way to achieve your goal should be something like :
Update S
Set S.Stock = S.Stock - I.Cantidad_Salida
From Stock S
Inner Join inserted I
On S.Sku = I.Sku

How I can get an auto incremented value

I have here a table that corresponds to the orders of the customers. I use AUTO_INCREMENT to determine the ID of the order. I have this SQL code to the orders table:
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL,
`customer_name` varchar(500) NOT NULL,
`order_total_price` decimal(20, 2) NOT NULL,
`order_date` varchar(100) NOT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB
What I need is to insert each of the products of that order in another table with a Foreign Key order_id to specify what order that products belongs to. The SQL code for the purchased_products table is:
CREATE TABLE IF NOT EXISTS `purchased_products` (
`order_id` int (11) NOT NULL,
FOREIGN KEY (`order_id`) REFERENCES orders(`order_id`),
`product_name` varchar(500) NOT NULL,
`product_price` decimal(20, 2) NOT NULL,
`product_quantity` int(11) NOT NULL,
PRIMARY KEY (`order_id`)
)
When the user buy something, I use this to insert the data in the orders table:
INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";
And here is my problem. I need to insert in the purchased_products table the products with the Order ID generated:
INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('*/The ID of the order need to goes here*/', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";
This is giving me a headache. I'm not really knowing how to do it. This should be done by a different way? How do I associate the order ID to the products belonging to it?
use function last_insert_id(). it will give you value that was auto-incremented as last one before call to it.
You can get the get the last inserted primary key value by using ##IDENTITY
Here's the MSDN article: https://msdn.microsoft.com/en-us/library/ms187342.aspx
USE AdventureWorks2012;
GO
--Display the value of LocationID in the last row in the table.
SELECT MAX(LocationID) FROM Production.Location;
GO
INSERT INTO Production.Location (Name, CostRate, Availability, ModifiedDate)
VALUES ('Damaged Goods', 5, 2.5, GETDATE());
GO
SELECT ##IDENTITY AS 'Identity';
GO
--Display the value of LocationID of the newly inserted row.
SELECT MAX(LocationID) FROM Production.Location;
GO
I would also recommend wrapping the statement in a TRANSACTION so that if any errors occur you can rollback.
As others have commented it depends on the RDBMS. In Oracle you typically use sequences. You create and store the sequence on the database and can use it on an INSERT by doing sequencename.nextval().
Sequences let you control starting values, increment/decrement size, caching and a lot more.
I did it by using PDO lastInsertId() to get the ID of last inserted order:
$sql = "INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";
$query = $connection->prepare($sql);
$query->execute();
$respective_order_id = $connection->lastInsertId();
And then:
INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('{$respective_order_id}', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";
Thanks for all who tried to help! They put me in the right way!
you can use SCOPE_IDENTITY() to retrieve the last identity you inserted within the current sql session.
here is another question with a great description of all the differences:
identity scope Question