Trying to create a database element via trigger - sql

Good morning,
I am developing an application with oracle apex and I have found the following issue:
I have created a form in order to insert a class called EXPEDIENTE in my database.
Whenever an EXPEDIENTE is created, a parent class for it must also be created automatically (EXPEDIENTE_GENERAL), and its ID (EXPEDIENTE_GENERAL_ID) must be set in EXPEDIENTE as its FK
I am trying to do this via Trigger in my database, but I keep receiving the error "FK missing" whenever I try to insert an EXPEDIENTE
The trigger should behave as follows :
Before insert EXPEDIENTE -> Create EXPEDIENTE_GENERAL -> Give EXPEDIENTE_GENERAL an ID -> Use that ID as FK in EXPEDIENTE .
This is what my trigger looks like now, but it's not working:
create or replace TRIGGER TV_EXPEDIENTES_TRI
BEFORE INSERT ON TV_EXPEDIENTES
FOR EACH ROW
DECLARE
id_exp_gen NUMBER;
BEGIN
SELECT TV_EXPEDIENTES_GENERALES_SEQ.nextval
INTO id_exp_gen
FROM dual;
INSERT INTO TV_EXPEDIENTES_GENERALES VALUES (id_exp_gen,'CAN');
SELECT TV_EXPEDIENTES_SEQ.nextval
INTO :new.C_ID_EXPEDIENTE
FROM dual;
:new.C_ID_EXPEDIENTE_GENERAL:=id_exp_gen;
END;
Thank you so much in advance.

I've just tried it, with such tables:
create table expediente_general
(id number primary key);
create table expediente
(id number primary key,
id_general number constraint fk_exgen references expediente_general (id)
);
Trigger:
create or replace trigger trg_bi_exp
before insert on expediente
for each row
begin
insert into expediente_general (id) values (:new.id_general);
end;
/
In Apex:
I created a form on a table (source is EXPEDIENTE),
set ID column to be a text column (it is hidden by default),
ran the page,
entered both ID and ID_GENERAL
pushed the CREATE button
The result:
SQL> select * from expediente;
ID ID_GENERAL
---------- ----------
1 100
SQL> select * from expediente_general;
ID
----------
100
SQL>
So ... it works.

Related

How to insert a newly generated id into another table with a trigger in postgresql?

Basically, users when they create a new record in mytable1, there is an id field that needs to be the same across multiple tables. I achieve this by having mytable2 with the s_id as primary key
My current function looks like
CREATE OR REPLACE FUNCTION test.new_record()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
case when new.s_id in (select s_id from mytable1) then
insert into mytable2 (sprn, date_created) select max(s_id) +1, now() from mytable2 ;
update mytable1 set new.s_id = (select max(b.s_id) from mytable2 b);
end case;
RETURN new;
END;
$function$;
Intended was when the s_id is replicated then it would create a new entry on mytable2. This new entry would then be updated onto mytable1
Problem with this function is that right now it does not recognise the new on the update part of the function.
How to keep the s_id take the value on every new insert ?
If you want to have one "generator" across multiple tables, create one sequence that is used across all those tables for the default value:
create sequence the_id_sequence;
create table one
(
id integer primary key default nextval('the_id_sequence')
.... other columns
);
create table two
(
id integer primary key default nextval('the_id_sequence')
.... other columns ...
);
If you want to replicate an ID from one table to another during insert, you only need one sequence:
create table one
(
-- using identity is the preferred over "serial" to auto-generate PK values
id integer primary key generated always as identity
);
create table two
(
id integer primary key
);
create or replace function insert_two()
returns trigger
as
$$
begin
insert into two (id) values (new.id);
return new;
end;
$$
language plpgsql;
create trigger replicate_id
before insert on one
for each row
execute procedure insert_two();
Then if you run:
insert into one (id) values (default);
A row with exactly the same id value will be inserted into table two.
If you don't have a generated ID column so far, use the following syntax:
alter table one
add testidcolumn bigint generated always as identity;

Oracle SQL error "ORA-00984: column not allowed here" when trying to replace a column

This question is not a duplicate from this one because even if the error messages are equal the answers there do not apply to my case.
I need to change a previous PK Id column defined as VARCHAR(36) NOT NULL to an incremental integer value. I'm trying to write a script to do this but when I run the alter table statement it fails with the error on the title.
The table is previously defined as:
CREATE TABLE journal_messages(
ID VARCHAR(36) NOT NULL, -- column to be changed
MESSAGE VARCHAR(2048) NOT NULL,
MESSAGE_TYPE VARCHAR(30) NOT NULL,
MSG_DATE TIMESTAMP NOT NULL,
MODULE_CODE INTEGER NOT NULL
);
ALTER TABLE journal_messages ADD (CONSTRAINT journal_messages_pk PRIMARY KEY (ID));
The script I'm running is:
DELETE FROM JOURNAL_MESSAGES;
ALTER TABLE JOURNAL_MESSAGES DROP COLUMN ID;
CREATE SEQUENCE journal_messages_seq START WITH 1;
ALTER TABLE JOURNAL_MESSAGES ADD (ID NUMBER(10) DEFAULT journal_messages_seq.nextval NOT NULL); -- error happens here
ALTER TABLE journal_messages ADD (
CONSTRAINT journal_messages_pk PRIMARY KEY (ID));
When I try to create a trigger it to update the incremental, it fails with SQL Error [4098] [42000]: ORA-04098: trigger 'TRG_SEQ_JOURNAL_MSG' is invalid and failed re-validation when I try to insert a new tuple:
ALTER TABLE JOURNAL_MESSAGES DROP COLUMN ID;
ALTER TABLE JOURNAL_MESSAGES ADD (ID NUMBER(10) NOT NULL);
create or replace trigger trg_seq_journal_msg
before insert on journal_messages
for each row
begin
:new.id := journal_messages_seq.nextval;
end;
/
INSERT INTO JOURNAL_MESSAGES (message, MESSAGE_TYPE, msg_date, MODULE_CODE) VALUES ('test', 'alteration', CURRENT_TIMESTAMP, '10');
Umm ... not like that, but like this:
once the table is empty, you don't have to drop the column - just modify its datatype
use a trigger to automatically set IDs value
If you were on 12c, you could have used identity column.
SQL> CREATE TABLE journal_messages(
2 ID VARCHAR(36) NOT NULL, -- column to be changed
3 MESSAGE VARCHAR(2048) NOT NULL,
4 MESSAGE_TYPE VARCHAR(30) NOT NULL,
5 MSG_DATE TIMESTAMP NOT NULL,
6 MODULE_CODE INTEGER NOT NULL
7 );
Table created.
SQL> delete from journal_Messages;
0 rows deleted.
SQL> alter table journal_messages modify (id number(10));
Table altered.
SQL> CREATE SEQUENCE journal_messages_seq START WITH 1;
Sequence created.
SQL> create or replace trigger trg_bi_joumes
2 before insert on journal_messages
3 for each row
4 begin
5 :new.id := journal_messages_seq.nextval;
6 end;
7 /
Trigger created.
SQL>
[EDIT: after reading your comment and saw your edition]
That still works OK - I literally copy/pasted your code and got this:
SQL> ALTER TABLE JOURNAL_MESSAGES DROP COLUMN ID;
Table altered.
SQL> ALTER TABLE JOURNAL_MESSAGES ADD (ID NUMBER(10) NOT NULL);
Table altered.
SQL> create or replace trigger trg_seq_journal_msg
2 before insert on journal_messages
3 for each row
4 begin
5 :new.id := journal_messages_seq.nextval;
6 end;
7 /
Trigger created.
SQL> INSERT INTO JOURNAL_MESSAGES (message, MESSAGE_TYPE, msg_date, MODULE_CODE) VALUES ('test', 'alteration', CURRENT_TIMESTAMP, '10')
2 ;
1 row created.
SQL>
As you can see, everything seems to be just fine. Try the following: recompile the trigger and show errors (if any; if so, please, post them here):
SQL> alter trigger trg_seq_journal_msg compile;
Trigger altered.
SQL> show err
No errors.
SQL>

Insert inserted id to another table

Here's the scenario:
create table a (
id serial primary key,
val text
);
create table b (
id serial primary key,
a_id integer references a(id)
);
create rule a_inserted as on insert to a do also insert into b (a_id) values (new.id);
I'm trying to create a record in b referencing to a on insertion to a table. But what I get is that new.id is null, as it's automatically generated from a sequence. I also tried a trigger AFTER insert FOR EACH ROW, but result was the same. Any way to work this out?
To keep it simple, you could also just use a data-modifying CTE (and no trigger or rule):
WITH ins_a AS (
INSERT INTO a(val)
VALUES ('foo')
RETURNING a_id
)
INSERT INTO b(a_id)
SELECT a_id
FROM ins_a
RETURNING b.*; -- last line optional if you need the values in return
Related answer with more details:
PostgreSQL multi INSERT...RETURNING with multiple columns
Or you can work with currval() and lastval():
How to get the serial id just after inserting a row?
Reference value of serial column in another column during same INSERT
Avoid rules, as they'll come back to bite you.
Use an after trigger on table a that runs for each row. It should look something like this (untested):
create function a_ins() returns trigger as $$
begin
insert into b (a_id) values (new.id);
return null;
end;
$$ language plpgsql;
create trigger a_ins after insert on a
for each row execute procedure a_ins();
Don't use triggers or other database Kung fu. This situation happens every moment somewhere in the world - there is a simple solution:
After the insertion, use the LASTVAL() function, which returns the value of the last sequence that was auto-incremented.
Your code would look like:
insert into a (val) values ('foo');
insert into b (a_id, val) values (lastval(), 'bar');
Easy to read, maintain and understand.

Tackling nested inserts using functions

Hi people i need some help deciding on the best way to do an insert into table ‘shop’ which has a serial id field. I also need to insert into tables ‘shopbranch’ and ‘shopproperties’ which both references shop.id.
In a nutshell I need to insert one shop record. Then two records for each table of the following tables, shopproperty and shopbranch, whose shopid (FK) references the just created shop.id field
I saw somewhere that i could wrap the ‘shop’ insert, inside a function called lets say ‘insert_shop’ which does the 'shop' insert and returns its id using a select statement
Then inside another function which inserts shoproperty and shopbranch records i could do one call to insert_shop function to return the shop id which can be used to be passed in as the shop id for the records.
Can you let me know if I’m looking at this in the correct way as I’m a newbie.
One way to approach this is to create a view on your three tables that shows all columns from all three tables that can be inserted or updated. If you then create an INSTEAD OF INSERT trigger on the view then you can manipulate the view contents as if it were a table. You can do the same with UPDATE and even combine the two into an INSTEAD OF INSERT OR UPDATE trigger. The function that your trigger calls then has three INSERT statements that redirect the insert on the view to the underlying tables:
CREATE TABLE shop (
id serial PRIMARY KEY,
nm text,
...
);
CREATE TABLE shopbranch (
id serial PRIMARY KEY,
shop integer NOT NULL REFERENCES shop,
branchcode text,
loc text,
...
);
CREATE TABLE shopproperties (
id serial PRIMARY KEY,
shop integer NOT NULL REFERENCES shop,
prop1 text,
prop2 text,
...
);
CREATE VIEW shopdetails AS
SELECT s.*, b.*, p.*
FROM shop s, shopbranch b, shopproperties p,
WHERE b.shop = s.id AND p.shop = s.id;
CREATE FUNCTION shopdetails_insert() RETURNS trigger AS $$
DECLARE
shopid integer;
BEGIN
INSERT INTO shop (nm, ...) VALUES (NEW.nm, ...) RETURNING id INTO shopid;
IF NOT FOUND
RETURN NULL;
END;
INSERT INTO shopbranch (shop, branchcode, loc, ...) VALUES (shopid, NEW.branchcode, NEW.loc, ...);
INSERT INTO shopproperties(shop, prop1, prop2, ...) VALUES (shopid, NEW.prop1, NEW.prop2, ...);
RETURN NEW;
END; $$ LANGUAGE plpgsql;
CREATE TRIGGER shopdetails_trigger_insert
INSTEAD OF INSERT
FOR EACH ROW EXECUTE PROCEDURE shopdetails_insert();
You could of course play with the view and show only those columns from the three tables that can be inserted or updated (such as excluding primary and foreign keys).

SQLPlus AUTO_INCREMENT Error

When I try and run the following command in SQLPlus:
CREATE TABLE Hotel
(hotelNo NUMBER(4) NOT NULL AUTO_INCREMENT,
hotelName VARCHAR(20) NOT NULL,
city VARCHAR(50) NOT NULL,
CONSTRAINT hotelNo_pk PRIMARY KEY (hotelNo));
I get the following error:
(hotelNo NUMBER(4) NOT NULL AUTO_INCREMENT,
*
ERROR at line 2:
ORA-00907: missing right parenthesis
What am I doing wrong?
Many will gripe about this not being a standard feature in Oracle, but when it’s as easy as two more commands after your CREATE TABLE command I can’t see any good reason to use fancy SQL on every insert.
First let’s create a simple table to play with.
SQL> CREATE TABLE test
(id NUMBER PRIMARY KEY,
name VARCHAR2(30));
Table created.
Now we’ll assume we want ID to be an auto increment field. First we need a sequence to grab values from.
SQL> CREATE SEQUENCE test_sequence
START WITH 1
INCREMENT BY 1;
Sequence created.
Now we can use that sequence in a BEFORE INSERT trigger on the table.
CREATE OR REPLACE TRIGGER test_trigger
BEFORE INSERT
ON test
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT test_sequence.nextval INTO :NEW.ID FROM dual;
END;
/
SQL> INSERT INTO test (name) VALUES ('Jon');
1 row created.
SQL> INSERT INTO test (name) VALUES (’Bork’);
1 row created.
SQL> INSERT INTO test (name) VALUES (’Matt’);
1 row created.
SQL> SELECT * FROM test;
ID NAME
———- ——————————
1 Jon
2 Bork
3 Matt
Oracle has no auto_increment, you need to use sequences.
Or - starting with Oracle 12.1 - you can simply have:
CREATE TABLE employee
(
id NUMBER GENERATED by default on null as IDENTITY
....
)