ORACLE SQL Status check trigger - sql

I wanted to create a trigger which when a new order is inserted in the ORDERS table the trigger updates the status level of a customer in the CUSTOMER table, depending on how many orders they have made. If a customer has 0 orders his status level is 'new' else if he has more than 1 he is a 'standard' customer.
The trigger below works if I add the customer_no in manually:
create or replace TRIGGER STATUS_CHECK
AFTER INSERT ON ORDERS
DECLARE
n INT;
BEGIN
SELECT COUNT(ORDER_NO)
INTO n
FROM ORDERS
INNER JOIN CUSTOMER
ON CUSTOMER.CUSTOMER_NO = ORDERS.CUSTOMER_CUSTOMER_NO
WHERE CUSTOMER.CUSTOMER_NO = '01';
IF(n > 1) THEN
UPDATE CUSTOMER
SET CUSTOMER.STATUS_LEVEL = 'STANDARD'
WHERE CUSTOMER.CUSTOMER_NO = '01';
END IF;
END;

Related

Trigger to insert multiple rows based on many-to-many relationship

I have three tables Reservation, Reservation_Passenger and Ticket.
Each reservation can have multiple passengers. I need to create a trigger to insert a ticket (according to the number of passengers) every time the Reservation status is updated to 'Booked'. How can I achieve it?
Reservation (reservationId, status)
Reservation_Passenger (reservationId, passengerId)
Ticket (ticketId, passengerId, issuedDate)
What I have tried:
CREATE
TRIGGER Generate_Ticket
ON Reservation
AFTER UPDATE
AS
DECLARE #reservationStatus varchar(15)
SELECT #reservationStatus = INSERTED.Status from INSERTED
IF #reservationStatus = 'Booked'
BEGIN
--stuck here
END
GO
The same way you store the status into a variable, you could also retrieve the reservationId
DECLARE #reservationStatus varchar(15)
DECLARE #reservationId int
SELECT #reservationId = INSERTED.reservationId,
#reservationStatus = INSERTED.Status
FROM INSERTED
Now in the part where you are stuck, to create a Ticket to every passenger on the reservation you can feed an INSERT with a SELECT of the related passengers.
INSERT INTO Ticket (passengerId, issuedDate)
SELECT passengerId, getdate()
FROM Reservation_Passenger
WHERE reservationId = #reservationId
PS You will need to be careful that your code doesn't change more than one reservation to booked on the same UPDATE command. Because in that case the trigger is only fired once, with all the updated reservations stored in the INSERTED dataset. You will need to use a CURSOR to loop through all those reservations to apply your logic, or switch to this simpler trigger that creates tickets for all the passengers of all the booked reservations in one single step:
CREATE TRIGGER Generate_Ticket ON Reservation AFTER UPDATE
AS
INSERT INTO Ticket (passengerId, issuedDate)
SELECT P.passengerId, getdate()
FROM INSERTED as R
INNER JOIN Reservation_Passenger as P on P.reservationId = R.reservationID
WHERE R.Status = 'Booked'
You should also be careful because the trigger fires when any field is updated on the Reservation table. If you were to update another field, for example a comment, on an already booked reservation, your trigger will duplicate all his tickets again.
I recommend you to check not only that INSERTED.Status = 'Booked', but also that DELETED.Status <> 'Booked', so you only create tickets when the Status field has changed to Booked from something else.
That would be :
CREATE TRIGGER Generate_Ticket ON Reservation AFTER UPDATE
AS
INSERT INTO Ticket (passengerId, issuedDate)
SELECT P.passengerId, getdate()
FROM INSERTED as I
INNER JOIN DELETED as D on D.reservationId = I.reservationID
INNER JOIN Reservation_Passenger as P on P.reservationId = I.reservationID
WHERE I.Status = 'Booked' and coalesce(D.Status, '') <> 'Booked'

Update multiple columns by ids

I have tables called tblPurchase and tblInvoice. When I Insert new record I want to update my TotalStock form tblInvoice. I tried following code.
Create procedure [dbo].[spUpdateTotalStock] #Stock int, #PurchaseId int
As
Begin
Begin Transaction
Update tblPurchase
Set TotalStock = #Stock
Where PurchaseId = #PurchaseId
RollBack Transaction
end
It worked as expected. But I want to update TotalStock column by many ids. It means when I insert more than one invoice at the same time, I want to update my TotalStock column. like this
tblInvoice
ItemName | Quantity
---------+----------
Phone 3
Mouse 6
tblPurchase
ItemName | TotalStock
-----------+------------
phone 3
Mouse 6
ID comes with parameter. Always more than 10 ids come with parameter.
When I Insert new record I want to update my TotalStock form tblInvoice
This would normally be handled via a trigger not a stored procedure. That would look something like this:
create trigger trig_invoice_update on tblInvoice
after insert, update, delete
begin
update p
set quantity = p.quantity + coalesce(i.quantity, 0) - coalesce(d.quantity, 0)
from tblPurchase p left join
(select i.itemName, sum(i.quantity) as quantity
from inserted i
group by i.itemName
) i
on p.itemName = i.itemName left join
(select d.itemName, sum(d.quantity) as quantity
from deleted d
group by d.itemName
) d
on p.itemName = d.itemName
where d.quantity <> 0 or i.quantity <> 0;
end;
This version handles inserts, updates, and deletes, but assumes that all items are already in the purchases table.

About how to create in Oracle Express - SQL. A trigger to update a column

I have a product table and a sales table. Inside the product I have (product_id, p_desc, qty_stock) and in the sales table I have (sale_id, producto_id, sale_p_qty) where sale_p_qty is the quantity that a customer buys from a certain product.
The question would be how can I make a trigger to update the qty_stock column value in the product table (this value would be the stock)? I can not do it. I can do a trigger that decrements, but only one value at a time. The correct one would be to get the sale_p_qty of table sales and decrement in qty_stock but I can not do that. Could you please give me a hand?
My attempt stopped at this (I did not do a procedure, I do not know if you need to in this case):
CREATE OR REPLACE TRIGGER trg_stock_ai AFTER INSERT OR UPDATE ON sale
FOR EACH ROW
declare
new_stock NUMBER (4);
--SELECT sale_p_qty INTO new_stock FROM sale
--SET new_stock = (SELECT sale_p_qty FROM sale);
BEGIN
SELECT sale_p_qty INTO new_stock FROM sale;
UPDATE product
SET qty_stock = qty_stock - new_stock
WHERE product.product_id =: NEW.product_id;
END;
You can do this in two steps:
CREATE OR REPLACE TRIGGER trg_stock_ai AFTER INSERT OR UPDATE ON sale
FOR EACH ROW
BEGIN
UPDATE product
SET qty_stock = (qty_stock - :NEW.sale_p_qty)
WHERE p.product_id = :NEW.product_id;
UPDATE product
SET qty_stock = (qty_stock + :OLD.sale_p_qty)
WHERE p.product_id = :OLD.product_id;
END;
This should work for both inserts and updates, even when product_id changes.

Select and Update in Stored Functions Postgresql

I created a stored function for fetching data:
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity NUMERIC)
AS $$
BEGIN
RETURN QUERY SELECT
invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as
sum_sold_quantity
FROM
invoice_item
WHERE
status='sold'
GROUP BY
invoice_id, item_id;
END; $$
LANGUAGE 'plpgsql';
How to store this data and using it to update the table below?
UPDATE invoice_item
SET sold_quantity = sum_sold_quantity
where invoice_id=invoiceid
and item_id = itemid;
How can we club these two queries (Select and update) in one stored function and execute to fetch all 500k records with the above three columns and update batch wise (like 10 000 records)
You can use the function directly in the UPDATE statement
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from sold_quantity() as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;
For just 500.000 rows, I wouldn't bother doing any batching at all. Just update all rows in a single statement.
In fact you don't really need a function to begin with:
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from (
select invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as sum_sold_quantity
FROM invoice_item
WHERE status='sold'
GROUP BY invoice_id, item_id;
) as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;

Trigger referring to another subelement table

In SQL Server there two tables: Invoices (InvoiceId, Number, Date, Customer, TotalValue) and InvoicesElements (InvoiceId, Good, Qty, Value).
Each transaction inserts one row into Invoices and one/many rows into InvoicesElements.
I need to set a trigger on the Invoices table that will raise an error and rollback transaction when Good in the InvoicesElements table is 'Bike' and Customer is 'ABC'.
Any help much appreciated.
Przemek
ALTER TABLE
InvoicesElements
ADD CONSTRAINT
CHK_GOOD
CHECK (good <> 'Bike' OR good IS NULL)
Update:
CREATE TRIGGER
TR_InvoicesElements_AIU
ON InvoicesElements
AFTER INSERT, UPDATE
AS
IF EXISTS
(
SELECT NULL
FROM INSERTED ie
JOIN Invoices inv
ON inv.id = ie.invoiceId
WHERE ie.good = 'bike'
AND inv.customer = 'ABC'
)
THROW 50000, 'Not sure why but you cannot sell bikes to ABC', 0
GO
CREATE TRIGGER
TR_Invoices_AIU
ON Invoices
AFTER INSERT, UPDATE
AS
IF EXISTS
(
SELECT NULL
FROM InvoiceElements ie
JOIN INSERTED inv
ON inv.id = ie.invoiceId
WHERE ie.good = 'bike'
AND inv.customer = 'ABC'
)
THROW 50000, 'Not sure why but you cannot sell bikes to ABC', 0
GO