PLS-00103: Encountered the symbol "¿" - sql

I am trying to make sure that my primary key auto increments. The code below is what I have tried so far.
create or replace trigger field_null
before insert on table
for each row
begin
if :new.number_id is null then
select number_id_SEQ.nextval into :new.number_id from table;
end if;
end;​

Instead of table in select query,try to use dual. Try this General Trigger syntax to create trigger for Auto-increment column
CREATE OR REPLACE TRIGGER %triggername%
BEFORE INSERT ON %tablename% FOR EACH ROW
BEGIN
SELECT %seqname%.NEXTVAL
INTO :NEW.%columnname%
FROM DUAL;
END;
%seqname% will be replaced with the name of the sequence.
%triggername% will be replaced with the name of the trigger.
%columnname% will be replaced with the name of the associated column.
And to Create Sequence, You can use the following syntax:-
CREATE SEQUENCE %seqname%
START WITH 1
INCREMENT BY 1;
Refer Here

Related

Auto-increment in Oracle table when insert in the same table

I have a table and I want to increment a column by 1 when I insert a row into the same table.
Table users - when I insert first row value of idusers is 1, and in second row value is 2 ....
This is the table
USERS
EMAIL primary key
USERNAME
PASSWORD
IDUSER and this the column I want to be AUTO_INCREMENT
I have tried this code
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
create or replace trigger incrementIdUser
before insert on users
for each row
begin
select seq_person.nextval into :new.IDUSER from users;
end;
But I get an error when I insert a row:
Erreur lors de l'enregistrement des modifications de la table "SOCIAL"."USERS" :
Ligne 1 : ORA-01403: no data found
ORA-01403: no data found
ORA-06512: at "SOCIAL.INCREMENTIDUSER", line 2
ORA-04088: error during execution of trigger 'SOCIAL.INCREMENTIDUSER'
ORA-06512: at line 1
Not like that, but
create or replace trigger incrementIdUser
before insert on users
for each row
begin
:new.iduser := seq_person.nextval;
end;
Code you wrote selects from users table (which is empty, hence NO_DATA_FOUND). If it contained more than a single row, you'd get TOO_MANY_ROWS (as you're selecting into a scalar variable (:new.iduser). Finally, there's danger of mutating table error as you can't select from a table which is just being modified (in this trigger type).
Insetead of select seq_person.nextval into :new.IDUSER from users; to assign sequence value into iduser you need to use :new.IDUSER :=seq_person.nextval;
create or replace trigger incrementIdUser
before insert on users
for each row
begin
:new.IDUSER :=seq_person.nextval;
end;
You get that error because there are zero rows in the USERS table so SELECT ... FROM USERS returns no rows.
What you want is to either use a table that will always return a single row (which, in Oracle, is the DUAL table):
create or replace trigger incrementIdUser
before insert on users
for each row
begin
select seq_person.nextval into :new.IDUSER from DUAL;
end;
Or, the better solution, is to not use an SQL statement and use pure PL/SQL:
create or replace trigger incrementIdUser
before insert on users
for each row
begin
:new.IDUSER := seq_person.nextval;
end;
Instead of using a trigger, you should use an identity column in the create table statement:
create table users
(iduser integer generated by default on null as identity (nomaxvalue nocache order),
...);

Adding (count) sequence value to column value via trigger in Oracle SQL

I would like to write a trigger which will be able to add sequence value to column value.
Example: Sequence value is 5 and column value in table is 45. Result after inserting new row should be 50.
Problem is that I dont know how to fetch value from the column and then add it to the sequence value in trigger code.
After using my trigger I am able to insert a new row which will create columns with value = 5.
CREATE SEQUENCE Adding_Seq
START WITH 5
INCREMENT BY 1;
CREATE OR REPLACE TRIGGER Adding_Trigger
BEFORE INSERT ON Table
FOR EACH ROW
BEGIN
SELECT Adding_Seq.nextval
INTO :new.Value
FROM dual;
END;
I tried to add some "+" in section SELECT or later in INTO with name of the column from table, but there were errors.
Is is possible to do something like this in trigger or not?
Thanks for you help!
This is really strange. But you can just use addition:
BEGIN
SELECT :new.Value + Adding_Seq.nextval INTO :new.Value
FROM dual;
END;

Use trigger to generate a primary key in oracle

New I want to create a trigger in my oracle database to generate the primary key for every new row. The pk contains two parts, the firset is to_char(sysdate, 'yyyyMMddHH24mmss') and the second part is an ID that is generated by a sequence, like to_char(SEQ_A_ID,FM000000). SEQ_A is an int sequence starts from 1 and the increment is 1. My pk data type is a varchar2(20) .
Now I write SQL like:
CREATE OR REPLACE TRIGGER "DEMO"."TRIGGER_A_ID" BEFORE INSERT ON "DEMO"."A" REFERENCING OLD AS "OLD" NEW AS "NEW" FOR EACH ROW ENABLE
BEGIN
select to_char(sysdate,‘yyyyMMddHH24mmss’) || to_char(SEQ_A_ID.nextval,'FM00000') into :new.id from dual;
END;;
The SQL above has some mistakes, but I don't know the right way to put the result of select statement into my pk.
create or replace trigger "DEMO"."TRIGGER_A_ID"
before insert on "DEMO"."A"
referencing old as "OLD" new as "NEW"
for each row enable
l_id varchar2(20);
begin
select to_char(sysdate, ‘yyyymmddhh24mmss’) || to_char(seq_a_id.nextval, 'FM00000')
into l_id
from dual;
:new.id:= l_new_id;
end;

Oracle - Insert New Row with Auto Incremental ID

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.

Behaviour of insertion trigger when defining autoincrement in Oracle

I have been looking for a way to define an autoincrement data type in Oracle and have found these questions on Stack Overflow:
Autoincrement in Oracle
Autoincrement Primary key in Oracle database
The way to use autoincrement types consists in defining a sequence and a trigger to make insertion transparent, where the insertion trigger looks so:
create trigger mytable_trg
before insert on mytable
for each row
when (new.id is null)
begin
select myseq.nextval into :new.id from dual;
end;
I have some doubts about the behaviour of this trigger:
What does this trigger do when the supplied value of "id" is different from NULL?
What does the colon before "new" mean?
I want the trigger to insert the new row with the next value of the sequence as ID whatever the supplied value of "new.id" is. I imagine that the WHEN statement makes the trigger to only insert the new row if the supplied ID is NULL (and it will not insert, or will fail, otherwise).
Could I just remove the WHEN statement in order for the trigger to always insert using the next value of the sequence?
The WHEN condition specifies a condition that must be TRUE for the trigger to fire. In this exampple, the trigger will only fire if the new row has a NULL IS. When the ID is not null, the trigger will not fire and so whatever value ID has been given in the insert statement will be left alone.
Yes, if you simply remove the WHEN condition then the trigger will always fire and so will always provide a sequence value for ID.
Nothing. That allows to specify a value manually.
It's a placeholder for the new value of the column.
You have 2 methods you can do:
if the table looks like this:
create table my_test (
id number,
my_test data varchar2(255)
);
and your sequence is this:
create sequence test_seq
start with 1
increment by 1
nomaxvalue;
you can create a trigger like this (with no When statement like Tony Andrews said)
create trigger test_trigger
before insert on my_test
for each row
begin
select test_seq.nextval into :new.id from dual;
end;
or you could just simply use this then you don't need a trigger:
insert into my_test values(test_seq.nextval, 'voila!');