When I try to create a trigger in Oracle 11g, I get the following errors:
ORA-06552: PL/SQL: COMPILATION UNIT ANALYSIS TERMINATED
ORA-06553: PLS-320: THE DECLARATION OF THIS TYPE OF THIS EXPRESSION IS INCOMPLETE OR MALFORMED.
I've tried changing the table name from EVENT to another table and the trigger compiles but my search for reserved keywords only indicates EVENTS though. Is something else wrong with the trigger?
CREATE TRIGGER GEN_EVENT_ID
BEFORE INSERT ON EVENT
FOR EACH ROW
BEGIN
:NEW.ID := EVENT_ID_SEQ.NEXTVAL;
END;
Table
CREATE TABLE EVENT (
ID NUMBER(19,0) NOT NULL,
TIMESTAMP TIMESTAMP NOT NULL,
NAME VARCHAR2(255)
);
Id appears in the v$RESERVED_WORDS view, which is the view of SQL keywords. Check this link for more information on this.
Select *
From V$RESERVED_WORDS
Where KEYWORD = 'ID'
While Id is not marked as Reserved in this view, there seems to be some problem with using column names that appear in that list for triggers as stated in this other SO question.
If you read it you will see the OP had the same problem but with timestamp. In the other SO question a workaround was suggested that worked for the OP. If you change the column name the problem should disappear.
Update
Seeing your table declaration, all of your column names appear in the V$RESERVED_WORDS. Particularly the timestamp column is the same one mentioned in the other SO question (see link above) as being problematic for triggers.
My suggestion is to rename both the table and its columns. For example:
Create Table my_EVENT (
event_Id Number(19,0) Not Null,
event_Timestamp Timestamp Not Null,
event_Name Varchar2(255)
);
Related
I'm running Postgres 11 on RDS.
I'm trying to create a simple trigger function to insert records into table 'test_alias' whenever a row is inserted into table 'test_values'.
I have the following tables:
CREATE TABLE the_schema.test_values (
id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
value_1 TEXT NOT NULL,
value_2 TEXT NOT NULL,
value_quantity INTEGER NOT NULL
);
CREATE TABLE the_schema.test_alias (
id INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now(),
value_1_copy TEXT NOT NULL,
value_2_copy TEXT NOT NULL,
value_quantity_copy INTEGER NOT NULL
);
My trigger function is like so:
CREATE OR REPLACE FUNCTION the_schema.populate_test_alias()
RETURNS TRIGGER AS
$BODY$
BEGIN
IF NEW.the_schema.test_values THEN
INSERT INTO the_schema.test_alias (value_1_copy, value_2_copy, value_quantity_copy)
VALUES (NEW.value_1, NEW.value_2, NEW.value_quantity);
END IF;
return null;
END;
$BODY$ LANGUAGE plpgsql;
And here is the trigger:
CREATE TRIGGER TRG_TEST_ALIAS
AFTER INSERT OR UPDATE ON the_schema.test_values
FOR EACH ROW
execute procedure the_schema.populate_test_alias();
Upon INSERT like so:
INSERT INTO the_schema.test_values (value_1, value_2, value_quantity)
VALUES ('abc', 'xyz', 1);
I get this error:
ERROR: missing FROM-clause entry for table "the_schema"
LINE 1: SELECT NEW.the_schema.test_values
I've also tried an equivalent setup with the default schema, and it still errors (though with a different error):
ERROR: record "new" has no field "test_values"
CONTEXT: SQL statement "SELECT NEW.test_values"
PL/pgSQL function populate_test_alias() line 3 at IF
It seems to me that there must be an error in the way I'm using the NEW keyword, but as far as I can tell, the way I've used it in the function is the same as several examples I've referred to (online/SO and hard copy), and I can't figure it out.
All guidance is much appreciated!
example of similar question for reference, includes links to official docs (which I've also read but clearly don't understand as I should):
[https://stackoverflow.com/questions/11001118/postgres-trigger-after-insert-accessing-new]
NEW references the inserted or updated row. Therefore NEW. only makes sense with a field identifier.
Also value_1, value_2 and value_quantity have a NOT NULL constraint, which means that you need not test for them.
So you can just drop the whole conditional:
CREATE OR REPLACE FUNCTION the_schema.populate_test_alias()
RETURNS TRIGGER AS
$BODY$
BEGIN
--IF NEW.the_schema.test_values THEN
INSERT INTO the_schema.test_alias (value_1_copy, value_2_copy, value_quantity_copy)
VALUES (NEW.value_1, NEW.value_2, NEW.value_quantity);
--END IF;
return null;
END;
$BODY$ LANGUAGE plpgsql;
Given this table:
create table test (
name text primary key
);
I need to write a plpgsql function with a variable name that collides with the primary key name, which I must use in a on conflict clause:
create or replace function func(
name text -- this variable name...
) returns void language plpgsql as
$$
begin
insert into test (name) values (name)
on conflict (name) do update -- ...conflicts with this line
set name = func.name;
end;
$$;
This compiles, but then throws an ambiguous column reference:
select * from func('one');
ERROR: column reference "name" is ambiguous
LINE 2: on conflict (name) do update
^
DETAIL: It could refer to either a PL/pgSQL variable or a table column.
QUERY: insert into test (name) values (name)
on conflict (name) do update
set name = func.name
CONTEXT: PL/pgSQL function func(text) line 3 at SQL statement
I tried specifying the full column name as on conflict (test.name) which does not compile, or ((test.name)) which compiles:
create or replace function func(
name text
) returns void language plpgsql as
$$
begin
insert into test (name) values (name)
on conflict ((test.name)) do -- this fails too
update set name = func.name;
end;
$$;
But it fails as well:
select * from func('two');
ERROR: invalid reference to FROM-clause entry for table "test"
LINE 2: on conflict ((test.name)) do
^
HINT: There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY: insert into test (name) values (name)
on conflict ((test.name)) do
update set name = func.name
CONTEXT: PL/pgSQL function func(text) line 3 at SQL statement
Is there a solution?
Edit: I found a workaround:
on conflict on constraint test_pkey do update
where test_pkey is the table name plus _pkey. I don't know how reliable this is though. I'd still like to specify the column name instead.
to start with, name is a bad name for both variable and attribute. When you have both, code won't look good. with that in mind, you can "prefix" variable with labeled block (in example below <<fn>>``), and setvariable_conflict` to give preference to column name, see code below:
t=# create or replace function func(
name text
) returns void language plpgsql as
$$
#variable_conflict use_column
<<fn>>
declare name text :='blah';
begin
insert into test (name) values (name)
on conflict (name) do -- this no longer fails
update set name = fn.name;
end;
$$;
t=# insert into test select 'b';
INSERT 0 1
Time: 8.076 ms
t=# select func('b');
func
------
(1 row)
Time: 6.117 ms
t=# select * from test;
name
------
b
blah
(2 rows)
https://www.postgresql.org/docs/current/static/plpgsql-implementation.html#PLPGSQL-VAR-SUBST
By default, PL/pgSQL will report an error if a name in a SQL statement
could refer to either a variable or a table column. You can fix such a
problem by renaming the variable or column, or by qualifying the
ambiguous reference, or by telling PL/pgSQL which interpretation to
prefer.
and further - basically the whole link is about it.
And yet - after demonstrating how particular task this can be easily done with plpgsql, I still quote namual:
The simplest solution is to rename the variable or column. A common
coding rule is to use a different naming convention for PL/pgSQL
variables than you use for column names. For example, if you
consistently name function variables v_something while none of your
column names start with v_, no conflicts will occur.
The ON CONFLICT... syntax (as documented here) uses a unique constraint to determine if the row conflicts. You can specify this unique constraint either by listing the columns it contains (at which point Postgres "infers" the correct index to use) or by naming the constraint directly.
In your case, the unique constraint being used is the primary key constraint implicitly created during your CREATE TABLE statement. This will have a name given to it by the DBMS, unless you specify one directly; so you will need to either look up the name the DBMS has given it (and be aware that this may change if you recreate the schema later), or name it explicitly when you create the table using the syntax CONSTRAINT pk_some_name PRIMARY KEY.
You would then specify the clause as ON CONFLICT ON CONSTRAINT pk_some_name DO ... (note no brackets around the constraint name).
(Alternatively, of course, you could change your function to use an unambiguous parameter name; personally, I think it's good practice to use a prefix like p_ or in_ rather than handling conflicts on a case-by-case basis.)
This question already has answers here:
What exactly do quotation marks around the table name do?
(2 answers)
Closed 5 years ago.
I'm trying to create a trigger in Oracle, but it's returning the error
ORA-00942: table or view does not exist
Here is the table:
CREATE TABLE quartos(
idQuarto NUMBER(11),
numeroQ NUMBER(11),
limitePessoas NUMBER(2),
valorDiaria NUMBER(10,2),
situacao NUMBER(1), CONSTRAINT idQuarto_pk PRIMARY KEY (idQuarto)
);
Here is the sequence:
CREATE sequence "quartos_seq";
And here is the trigger:
CREATE trigger "bi_quartos"
before insert on "quartos"
for each row
begin
select "quartos_seq".nextval into :NEW."idQuarto" from dual;
end;
I've creatend another trigger before the same way and nothing went wrong. I just changed the parameters and now its returning that error
remove the double quotes from
CREATE trigger "bi_quartos"
before insert on "quartos"
Tables names are converted to upper case. What you are doing is forcing it to search a table with lower case which doesn't exist.
You're mixing case sensitive and case insensitive identifiers for your table and column names.
If you don't wrap the original declarations in double-quotes, the are created as case insensitive and you can't use double-quotes when you try and use them:
CREATE or replace trigger "bi_quartos"
before insert on quartos
for each row
begin
select "quartos_seq".nextval into :new.idQuarto from dual;
end;
I am trying to create a trigger to save rows that I delete into a separate table, but I am facing constant errors. I am using postgresSQL (terminal).
Here is what the original table looks like:
CREATE TABLE person_Lives_there
(
pId BIGINT NOT NULL,
cityId BIGINT NOT NULL
);
And my protocol table
CREATE TABLE Protocol
(
pId BIGINT NOT NULL,
cityId BIGINT NOT NULL,
deletedOn TIMESTAMP
);
Now, my trigger should look like this, but it constantly gives me errors, right now:
ERROR: syntax error at or near "INSERT"
Code:
CREATE TRIGGER deletion
AFTER DELETE
ON person_Lives_there
FOR EACH ROW
INSERT INTO Protocol (pId, cityId, deletedOn)
VALUES (old.pId, old.cityId, current_date());
I have also already tried to have a trigger and a function, but that led to constant error messages with the function.
Thank you for your help.
PostgreSQL allows only procedural triggers. SQL statement triggers are not supported.
CREATE OR REPLACE FUNCTION person_Lives_there_delete_trg_fx()
RETURNS trigger AS $$
BEGIN
INSERT INTO Protocol
VALUES(old.PId, old.cityId, current_date());
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER person_Lives_there_delete_trg
AFTER DELETE ON person_Lives_there
FOR EACH ROW
EXECUTE PROCEDURE person_Lives_there_fx();
I have a workqueue table that has a workid column. The workID column has values that increment automatically. Is there a way I can run a query in the backend to insert a new row and have the workID column increment automatically?
When I try to insert a null, it throws error ORA01400 - Cannot insert null into workid.
insert into WORKQUEUE (facilitycode,workaction,description) values ('J', 'II', 'TESTVALUES')
What I have tried so far - I tried to look at the table details and didn't see any auto-increment. The table script is as follow
"WORKID" NUMBER NOT NULL ENABLE,
Database: Oracle 10g
Screenshot of some existing data.
ANSWER:
I have to thank each and everyone for the help. Today was a great learning experience and without your support, I couldn't have done. Bottom line is, I was trying to insert a row into a table that already has sequences and triggers. All I had to do was find the right sequence, for my question, and call that sequence into my query.
The links you all provided me helped me look these sequences up and find the one that is for this workid column. Thanks to you all, I gave everyone a thumbs up, I am able to tackle another dragon today and help patient care take a step forward!"
This is a simple way to do it without any triggers or sequences:
insert into WORKQUEUE (ID, facilitycode, workaction, description)
values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')
It worked for me but would not work with an empty table, I guess.
To get an auto increment number you need to use a sequence in Oracle.
(See here and here).
CREATE SEQUENCE my_seq;
SELECT my_seq.NEXTVAL FROM DUAL; -- to get the next value
-- use in a trigger for your table demo
CREATE OR REPLACE TRIGGER demo_increment
BEFORE INSERT ON demo
FOR EACH ROW
BEGIN
SELECT my_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/
There is no built-in auto_increment in Oracle.
You need to use sequences and triggers.
Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")
ELXAN#DB1> create table cedvel(id integer,ad varchar2(15));
Table created.
ELXAN#DB1> alter table cedvel add constraint pk_ad primary key(id);
Table altered.
ELXAN#DB1> create sequence test_seq start with 1 increment by 1;
Sequence created.
ELXAN#DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
select test_seq.nextval into :new.id from dual;
end;
/ 2 3 4 5 6 7 8
Trigger created.
ELXAN#DB1> insert into cedvel (ad) values ('nese');
1 row created.
You can use either SEQUENCE or TRIGGER to increment automatically the value of a given column in your database table however the use of TRIGGERS would be more appropriate. See the following documentation of Oracle that contains major clauses used with triggers with suitable examples.
Use the CREATE TRIGGER statement to create and enable a database trigger, which is:
A stored PL/SQL block associated with a table, a schema, or the
database or
An anonymous PL/SQL block or a call to a procedure implemented in
PL/SQL or Java
Oracle Database automatically executes a trigger when specified conditions occur. See.
Following is a simple TRIGGER just as an example for you that inserts the primary key value in a specified table based on the maximum value of that column. You can modify the schema name, table name etc and use it. Just give it a try.
/*Create a database trigger that generates automatically primary key values on the CITY table using the max function.*/
CREATE OR REPLACE TRIGGER PROJECT.PK_MAX_TRIGGER_CITY
BEFORE INSERT ON PROJECT.CITY
FOR EACH ROW
DECLARE
CNT NUMBER;
PKV CITY.CITY_ID%TYPE;
NO NUMBER;
BEGIN
SELECT COUNT(*)INTO CNT FROM CITY;
IF CNT=0 THEN
PKV:='CT0001';
ELSE
SELECT 'CT'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
FROM CITY;
END IF;
:NEW.CITY_ID:=PKV;
END;
Would automatically generates values such as CT0001, CT0002, CT0002 and so on and inserts into the given column of the specified table.
SQL trigger for automatic date generation in oracle table:
CREATE OR REPLACE TRIGGER name_of_trigger
BEFORE INSERT
ON table_name
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
SELECT sysdate INTO :NEW.column_name FROM dual;
END;
/
the complete know how, i have included a example of the triggers and sequence
create table temasforo(
idtemasforo NUMBER(5) PRIMARY KEY,
autor VARCHAR2(50) NOT NULL,
fecha DATE DEFAULT (sysdate),
asunto LONG );
create sequence temasforo_seq
start with 1
increment by 1
nomaxvalue;
create or replace
trigger temasforo_trigger
before insert on temasforo
referencing OLD as old NEW as new
for each row
begin
:new.idtemasforo:=temasforo_seq.nextval;
end;
reference:
http://thenullpointerexceptionx.blogspot.mx/2013/06/llaves-primarias-auto-incrementales-en.html
For completeness, I'll mention that Oracle 12c does support this feature. Also it's supposedly faster than the triggers approach. For example:
CREATE TABLE foo
(
id NUMBER GENERATED BY DEFAULT AS IDENTITY (
START WITH 1 NOCACHE ORDER ) NOT NULL ,
name VARCHAR2 (50)
)
LOGGING ;
ALTER TABLE foo ADD CONSTRAINT foo_PK PRIMARY KEY ( id ) ;
Best approach: Get the next value from sequence
The nicest approach is getting the NEXTVAL from the SEQUENCE "associated" with the table. Since the sequence is not directly associated to any specific table,
we will need to manually refer the corresponding table from the sequence name convention.
The sequence name used on a table, if follow the sequence naming convention, will mention the table name inside its name. Something likes <table_name>_SEQ. You will immediately recognize it the moment you see it.
First, check within Oracle system if there is any sequence "associated" to the table
SELECT * FROM all_sequences
WHERE SEQUENCE_OWNER = '<schema_name>';
will present something like this
Grab that SEQUENCE_NAME and evaluate the NEXTVAL of it in your INSERT query
INSERT INTO workqueue(id, value) VALUES (workqueue_seq.NEXTVAL, 'A new value...')
Additional tip
In case you're unsure if this sequence is actually associated with the table, just quickly compare the LAST_NUMBER of the sequence (meaning the current value) with the maximum id of
that table. It's expected that the LAST_NUMBER is greater than or equals to the current maximum id value in the table, as long as the gap is not too suspiciously large.
SELECT LAST_NUMBER
FROM all_sequences
WHERE SEQUENCE_OWNER = '<schema_name>' AND SEQUENCE_NAME = 'workqueue_seq';
SELECT MAX(ID)
FROM workqueue;
Reference: Oracle CURRVAL and NEXTVAL
Alternative approach: Get the current max id from the table
The alternative approach is getting the max value from the table, please refer to Zsolt Sky answer in this same question
This is a simple way to do it without any triggers or sequences:
insert into WORKQUEUE (ID, facilitycode, workaction, description)
values ((select count(1)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES');
Note : here need to use count(1) in place of max(id) column
It perfectly works for an empty table also.