how to insert row on table B when table A is updated, using a trigger in SQLlite - sqlite

Table A
userID
Name
Table B
UserID
Timestamp
I need to create a trigger to insert a row in table B, when A.Name changes. so far, i have:
CREATE TRIGGER NameUpdate
AFTER UPDATE OF Name
ON A
FOR EACH ROW
BEGIN
INSERT INTO B(
UserID,
Timestamp
)
VALUES (
xxxxxxx,
DateTime('now')
);
END;
XXXXXXX should be A.UserID that just changed.

You can refer to the before/after values (according to relevance i.e. only new for inserts, old or new for updates and only old for deletes) using a prefix of old. or new. respectively.
Try :-
CREATE TRIGGER NameUpdate AFTER UPDATE OF Name ON A FOR EACH ROW
BEGIN
INSERT INTO B( UserID, Timestamp ) VALUES ( new.UserID, DateTime('now') );
END
;
Or (as the UserID column hasn't changed) :-
CREATE TRIGGER NameUpdate AFTER UPDATE OF Name ON A FOR EACH ROW
BEGIN
INSERT INTO B( UserID, Timestamp ) VALUES ( old.UserID, DateTime('now') );
END
;

Related

Oracle Apex - REST data source - nested JSON array - trigger two tables - delete function error ORA-04091

This question is a follow up to another SO question.
I have an app with a REST Data Source taking in JSON responses from an API. There are two tables ORDERS and ORDER_ITEMS. The ORDERS table contains a column ORDER_ITEMS which is a JSON Document type.
I created a trigger on my ORDERS table which runs AFTER INSERT, UPDATE or DELETE on my ORDERS table, and which maintains the ORDER_ITEMS table (Extracts the JSON array from the ORDERS table ORDER_ITEMS column and inserts into ORDER_ITEMS table and each column).
create or replace trigger "TR_MAINTAIN_LINES"
AFTER
insert or update or delete on "ORDERS_LOCAL"
for each row
begin
if inserting or updating then
if updating then
delete ORDER_ITEMS_LOCAL
where order_id = :old.order_id;
end if;
insert into ORDER_ITEMS_LOCAL ( order_id, line_id, line_number, product_id, quantity, price)
( select :new.order_id,
seq_line_id.nextval,
j.line_number,
j.product_id,
j.quantity,
j.price
from json_table(
:new.order_items,
'$[*]' columns (
line_id for ordinality,
line_number number path '$.line_number',
product_id number path '$.product_id',
quantity number path '$.quantity',
price number path '$.price' ) ) j );
elsif deleting then
delete ORDER_ITEMS_LOCAL
where order_id = :old.order_id;
end if;
end;
The trigger works for AFTER INSERT and UPDATE. However, when I try to DELETE a row from the ORDERS table, I receive an error. error ORA-04091: table WKSP_DEMO.ORDER_ITEMS_LOCAL is mutating, trigger/function may not see it
But deleting a row from the ORDER_ITEMS table works as expected.
ORDERS table
enter image description here
ORDERS table data
enter image description here
ORDER_ITEMS table
enter image description here
ORDER_ITEMS table data
enter image description here
Triggers enter image description here
BI_ORDER_ITEMS_LOCAL trigger
create or replace trigger "BI_ORDER_ITEMS_LOCAL"
before insert on "ORDER_ITEMS_LOCAL"
for each row
begin
if :NEW."LINE_ID" is null then
select "ORDER_ITEMS_LOCAL_SEQ".nextval into :NEW."LINE_ID" from sys.dual;
end if;
end;
Error Message enter image description here
---- UPDATE ------
So I took out the delete portion of the trigger and both ORDER and ORDER_LINES table rows get deleted as expected.
create or replace trigger "TR_MAINTAIN_LINES"
AFTER
insert or update on "ORDERS_LOCAL"
for each row
begin
if inserting or updating then
if updating then
delete ORDER_ITEMS_LOCAL
where order_id = :old.order_id;
end if;
insert into ORDER_ITEMS_LOCAL ( order_id, line_id, line_number, product_id, quantity, price)
( select :new.order_id,
seq_line_id.nextval,
j.line_number,
j.product_id,
j.quantity,
j.price
from json_table(
:new.order_items,
'$[*]' columns (
line_id for ordinality,
line_number number path '$.line_number',
product_id number path '$.product_id',
quantity number path '$.quantity',
price number path '$.price' ) ) j );
end if;
end;
you have a conflict between the ON DELETE CASCADE clause and your trigger logic. In the DELETE case, both attempt to delete the child rows. You can ...
remove the DELETE section from your trigger and let the ON DELETE CASCADE clause do the job
remove the ON DELETE CASCADE clause from your foreign key.
I think, I'd recommend the second option, so that all that logic is in one place, i.e. your trigger.

Oracle 11g Triggers

I have create a table person(id, name ,samenamecount).The samenamecount attribute can be null but for each row can store the row count for same names.I am achieving this by calling a stored procedure inside a after insert trigger.Below is my code.
create or replace procedure automatic(s in person.name%type)
AS
BEGIN
update person set samenamecount=(select count(*) from person where name=s) where name=s;
END;
create or replace trigger inserttrigger
after insert
on person
for each row
declare
begin
automatic(:new.name);
end;
On inserting a row it is giving error like
table ABCD.PERSON is mutating, trigger/function may not see it.
Can somebody help me to figure out this?
If you have the table:
CREATE TABLE person (
id NUMBER
GENERATED ALWAYS AS IDENTITY
CONSTRAINT person__id__pk PRIMARY KEY,
name VARCHAR2(20)
NOT NULL
);
Then rather than creating a trigger, instead, you could use a view:
CREATE VIEW person_view (
id,
name,
samenamecount
) AS
SELECT id,
name,
COUNT(*) OVER (PARTITION BY name)
FROM person;
You can use the trigger:
CREATE TRIGGER inserttrigger
AFTER INSERT ON person
BEGIN
MERGE INTO person dst
USING (
SELECT ROWID AS rid,
COUNT(*) OVER (PARTITION BY name) AS cnt
FROM person
) src
ON (src.rid = dst.ROWID)
WHEN MATCHED THEN
UPDATE SET samenamecount = src.cnt;
END;
/
fiddle
If you want to make it more efficient then you could use a compound trigger and collate the names that are being inserted and only update the matching rows.

Create composed unique key field with trigger after insert in SQLITE

I have a table with multiple columns and one (unique key) should be a value composed from the values of other two columns.
CREATE TABLE batches (
id TEXT PRIMARY KEY UNIQUE,
name TEXT NOT NULL,
project_id INTEGER);
On each insert, I want to generate the id based on the value of 'name' and 'project_id' (this one can be null):
INSERT INTO batches (name,project_id) VALUES
('21.01',NULL),
('21.01',1),
('21.02',2);
So, I have created a table TRIGGER but doesn't execute.
CREATE TRIGGER create_batches_id
AFTER INSERT ON batches FOR EACH ROW
BEGIN
UPDATE batches
SET id = SELECT quote(name ||"_"|| (CASE project_id
WHEN NULL THEN '' ELSE project_id END )
FROM batches WHERE rowid = (SELECT MAX(rowid) FROM batches))
WHERE rowid = (SELECT MAX(rowid) FROM batches);
END;
Error:
SQL Error [1]: [SQLITE_ERROR] SQL error or missing database (near "SELECT": syntax error)
I expect:
id = 21.01_
id = 21.01_1
id = 21.01_2
What am I doing wrong? If I run only the SELECT/CASE statment it returns ok: '21.01_2'
I have also tried without the quote() function, no success.
UPDATE I:
I have managed to execute the whole create trigger statement (parenthesis were missing):
CREATE TRIGGER create_batch_id
AFTER INSERT ON batches FOR EACH ROW
BEGIN
UPDATE batches
SET id = (SELECT name ||"_"|| (CASE project_id WHEN NULL THEN 0 ELSE project_id END ) FROM batches WHERE rowid = (SELECT MAX(rowid) FROM batches) )
WHERE rowid = (SELECT MAX(rowid) FROM batches);
END;
It seems my editor (DBeaver) has a glitch with the following new line character. If it is inside the selection it runs into this exception (or I am missing something):
SQL Error [1]: [SQLITE_ERROR] SQL error or missing database (incomplete input)
If I manually select only the above lines (from CREATE to ;), the trigger is created, however, not the expected result. If value in project_id is NULL, no id value is created.
Don't add the column id in the table.
Instead define the combination of name and project_id as the PRIMARY KEY of the table, so that it is also UNIQUE:
CREATE TABLE batches (
name TEXT NOT NULL,
project_id INTEGER,
PRIMARY KEY(name, project_id)
)
Then, whenever you need that id you can run a query:
SELECT name || '_' || COALESCE(project_id, '') AS id,
name,
project_id
FROM batches
Or create a view:
CREATE VIEW v_batches AS
SELECT name || '_' || COALESCE(project_id, '') AS id,
name,
project_id
FROM batches
and query the view:
SELECT * FROM v_batches
See the demo.
Or if your version of SQLite is 3.31.0+ you can have the column id as a generated column:
CREATE TABLE batches (
name TEXT NOT NULL,
project_id INTEGER,
id TEXT GENERATED ALWAYS AS (name || '_' || COALESCE(project_id, '')),
PRIMARY KEY(name, project_id)
);

SQLite - Inserting values from multiple rows in the same table into a single row in another table

I have a table of phone numbers (tblPhoneNumbers):
ID, UserID, PhoneNumber
and I need to move them into a Users table (tblUsers) that contains:
ID, PhoneNumber1, PhoneNumber2
tblPhoneNumbers is assumed to have 2 rows for every user. Is it possible to move the PhoneNumber value of the first row into PhoneNumber1, and the PhoneNumber value of the second row into PhoneNumber2?
Essentially this is reverse-normalization but this is the task I need help with.
Thanks!
I need to use SQLite so I cannot use any syntax not available to SQLite.
If you're using sqlite 3.25 or better, you can use window functions to do it all in one statement (I assume here that the UserID column from tblPhoneNumbers is a foreign key that references ID from tblUsers, and that the given userid already has a record in that table; adjust as needed):
WITH allnumbers AS
(SELECT UserID
, PhoneNumber
, row_number() OVER (PARTITION BY UserID) AS num
FROM tblPhoneNumbers)
UPDATE tblUsers AS t
SET PhoneNumber1 = (SELECT a.PhoneNumber
FROM allnumbers AS a
WHERE a.UserID = t.ID AND num = 1)
, PhoneNumber2 = (SELECT a.PhoneNumber
FROM allnumbers AS a
WHERE a.UserID = t.ID AND num = 2);
(And if your system only has an older version that don't support window functions, you can always download a copy of the latest version of the sqlite3 shell and use it instead of the OS provided one).
(edit: You'll want an index on tblPhoneNumbers.UserID for better performance)
You could use the following :-
-- Create a temporary swap table
CREATE TEMP TABLE IF NOT EXISTS swapPhoneNumbers (ID INTEGER PRIMARY KEY, UserID INTEGER, PhoneNumber TEXT, replacementPhoneNumber TEXT);
-- Clear the temporary swap table in case it's used more than once
DELETE FROM swapPhoneNumbers;
-- Populate the temporary swap table according to the original data
INSERT INTO swapPhoneNumbers (ID,UserID,PhoneNumber) SELECT * FROM tblPhoneNumbers;
-- Update the swap table to include the replacement phone numbers
UPDATE swapPhoneNumbers SET replacementPhoneNumber = (
SELECT PhoneNumber FROM tblPhoneNumbers
WHERE swapPhoneNumbers.userID = tblPhoneNumbers.userID
AND swapPhoneNumbers.ID <> tblPhoneNumbers.ID
);
-- Update the original table with the new phone numbers
UPDATE tblPhoneNumbers SET PhoneNumber = (
SELECT replacementPhoneNumber FROM swapPhoneNumbers
WHERE tblPhoneNumbers.ID = swapPhoneNumbers.ID
);
The following is the SQL used to test the above.
-- Create Testing Table with some data
DROP TABLE IF EXISTS tblphoneNumbers;
CREATE TABLE IF NOT EXISTS tblPhoneNumbers (ID INTEGER PRIMARY KEY, userID INTEGER, PhoneNumber TEXT);
INSERT INTO tblPhoneNumbers (userID, PhoneNumber) VALUES
(1,'0111111111'),(1,'0222222222'),(2,'0333333333'),(2,'0444444444'),(3,'0555555555'),(3,'0666666666')
;
-- Show what is in the original table
SELECT * FROM tblPhoneNumbers;
-- Create a temporary swap table
CREATE TEMP TABLE IF NOT EXISTS swapPhoneNumbers (ID INTEGER PRIMARY KEY, UserID INTEGER, PhoneNumber TEXT, replacementPhoneNumber TEXT);
-- Clear the temporary swap table in case it's used more than once
DELETE FROM swapPhoneNumbers;
-- Populate the temporary swap table according to the original data
INSERT INTO swapPhoneNumbers (ID,UserID,PhoneNumber) SELECT * FROM tblPhoneNumbers;
-- Show what is in the swap table
SELECT * FROM swapPhoneNumbers;
-- Update the swap table to include the replacement phone numbers
UPDATE swapPhoneNumbers SET replacementPhoneNumber = (
SELECT PhoneNumber FROM tblPhoneNumbers
WHERE swapPhoneNumbers.userID = tblPhoneNumbers.userID
AND swapPhoneNumbers.ID <> tblPhoneNumbers.ID
);
-- Show what is now in the swap table
SELECT * FROM swapPhoneNumbers;
-- Update the original table with the new phone numbers
UPDATE tblPhoneNumbers SET PhoneNumber = (
SELECT replacementPhoneNumber FROM swapPhoneNumbers
WHERE tblPhoneNumbers.ID = swapPhoneNumbers.ID
);
-- Show what is in the original table
SELECT * FROM tblPhoneNumbers;
And this is some screen shots from doing it

trigger to delete a record before insert

i have a table with 4 columns
1.msisdn
2.accountnumber
3.cardnumber
4.subscriptiondate
I want to add a trigger to this table. If the data i am inserting is
1.99999999
2.2
3.3298572857239
4.(this can be blank)
and the data that is currently in the table is
1.99999999
2.1
3.3298572857239
4.(this can be blank)
Trigger should check if there is this msisdn 99999999 is already having a record with this cardnumber 3298572857239. If there is a record already existing in the table, the trigger should delete the existing entry and insert the new one. The final result should look like this
1.99999999
2.1
3.3298572857239
4.(this can be blank)
I want to keep the value of accountnumber same before and after the trigger. This is what i have tried so far but for this trigger, i am not getting any data in accountnumber column. Please someone help
DROP TRIGGER TRIG_TABLEA;
CREATE OR REPLACE TRIGGER TRIG_TABLEA
BEFORE INSERT ON TABLEA
REFERENCING OLD AS Old NEW AS New
FOR EACH ROW
BEGIN
:new.accountnumber := :old.accountnumber;
DELETE FROM TABLEA WHERE MSISDN = :new.MSISDN AND CARDNUMBER = :new.CARDNUMBER;
:new.MSISDN := :new.MSISDN;
:new.CARDNUMBER := :new.CARDNUMBER;
:new.accountnumber := :old.accountnumber;
END;
/
Don't do a delete-and-insert. You want MERGE. The only thing that can change in your statement is accountnumber and subscriptiondate. You don't say where the data is coming from, so I assume this is a PL/SQL procedure with p_* as the parameters. So you want something like this:
MERGE INTO mytable trg
USING ( SELECT p_accountnumber, p_subscriptiondate FROM dual ) src
ON ( trg.msisdn = p_msisdn AND trg.cardnumber )
WHEN NOT MATCHED INSERT ( msisdn, accountnumber, cardnumber, subscriptiondate )
VALUES ( p_msisdn, p_accountnumber, p_cardnumber, p_subscriptiondate )
WHEN MATCHED SET ( cardnumber = p_cardnumber, subscriptiondate = p_subscriptiondate)
This will do an insert if the row doesn't exist or update an existing row if it does.

Resources