How can I insert a sequence number automatically in Oracle Sql? [duplicate] - oracle

This question already has answers here:
How to create id with AUTO_INCREMENT on Oracle?
(18 answers)
Closed 7 years ago.
I have some table and trying load data into it by selecting row from another table like below.
insert into emp2(eid,ename,sal,my_seq_num) select eid,ename,sal from emp1;
When I executed the above query I am getting the error 'not enough values' because I selected only three rows but insert contains 4 columns .So my question is how can Insert a sequence number automatically (like we write SYSDATE to write into date column) .

insert into emp2(eid,ename,sal,my_seq_num)
select eid,ename,sal,sequence_name.nextval
from emp1;

insert into emp2(eid,ename,sal,my_seq_num) select eid,ename,sal,mention your
sequence name from emp1;
For example :-
insert into emp2(eid,ename,sal,my_seq_num) select eid,ename,sal,my_seq_num.nextval from emp1;

First, you need create a SEQUENCE object
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;
In your case:
CREATE SEQUENCE my_sequence
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;
Then, you can get the next number in the sequence with nextval, like:
SELECT my_sequence.NEXTVAL FROM DUAL
In your INSERT:
insert into emp2(eid,ename,sal,my_seq_num)
select eid,ename,sal,my_sequence.NEXTVAL from emp1;
Good Luck!

Related

How to increment the value of the unique constraint column value in ORACLE

How to increment the value of the unique constraint column value in ORACLE, in the select statement.
For example, in a table 'BILLING_TABLE' - column BLNG_Sk is the unique key (Autoincremented).
So while inserting a new record into the BILLING_TABLE, for the column BLNG_SK we need to give the value (Which is the increment by 1 from the present max value.)
For example, if BLNG_SK max value is 12321.
new record should be 12322.
how to achieve this in Oracle?
Oracle has a SEQUENCE object which provides the functionality you require.
You create one using the CREATE SEQUENCE SQL statement.
The Oracle documentation provides all the required information and the documentation is available via Oracle's Web site.
Assuming you are on Oracle 12.1 or later, define it as an identity column and do not pass any value when inserting:
create table testtable
( test_id number generated always as identity
constraint testtable_pk primary key
, othercol varchar2(10) );
insert into testtable (othercol) values ('Demo');
select * from testtable;
TEST_ID OTHERCOL
---------- ----------
1 Demo
insert into testtable (othercol) values ('Demo #2');
select * from testtable;
TEST_ID OTHERCOL
---------- ----------
1 Demo
2 Demo #2
Try creating a sequence and a trigger. This is the case when you provide the value manually.
CREATE SEQUENCE dept_seq START WITH 12322;
Trigger definition:
CREATE OR REPLACE TRIGGER dept_bir
BEFORE INSERT ON BILLING_TABLE
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/

Difference between Oracle sequence last number and max id inserted

I'm working on a application used by multiple users. They can insert, delete and update rows in the database which fires triggers what write into log tables. The problem is that the difference between the maximum id inserted in the log table and the last number generated by the sequences used by the trigger is changing continously. Sometimes an primary key exception is generated because the the sequence generate values that are already inserted in the table.
CREATE OR REPLACE
TRIGGER EVALUACION.TCALIF_DEL
AFTER DELETE ON EVALUACION.CALIFICACIONES FOR EACH ROW
BEGIN
INSERT INTO LOG_CALIFICACIONES (ID_BITACORA, ID_EVALUACION, ANIO, CALIFICACION, OBSERVACION, USUARIO, FECHA_HORA, TIPO_OPERACION_BD)
SELECT SEQ_CALIF.NEXTVAL, :OLD.ID_EVALUACION, :OLD.ANIO, :OLD.CALIFICACION, :OLD.OBSERVACION, :OLD.USUARIO, :OLD.FECHA_HORA, 'D' FROM DUAL;
END;
CREATE OR REPLACE
TRIGGER EVALUACION.TCALIF_INS
AFTER INSERT ON EVALUACION.CALIFICACIONES FOR EACH ROW
BEGIN
INSERT INTO LOG_CALIFICACIONES (ID_BITACORA, ID_EVALUACION, ANIO, CALIFICACION, OBSERVACION, USUARIO, FECHA_HORA, TIPO_OPERACION_BD)
SELECT SEQ_CALIF.NEXTVAL, :OLD.ID_EVALUACION, :OLD.ANIO, :OLD.CALIFICACION,:OLD.OBSERVACION, :OLD.USUARIO, :OLD.FECHA_HORA, 'I' FROM DUAL;
END;
CREATE OR REPLACE
TRIGGER EVALUACION2010.TCALIF_UPD
AFTER UPDATE ON EVALUACION.CALIFICACIONES FOR EACH ROW
BEGIN
INSERT INTO LOG_CALIFICACIONES (ID_BITACORA, ID_EVALUACION, ANIO, CALIFICACION, OBSERVACION, USUARIO, FECHA_HORA, TIPO_OPERACION_BD)
SELECT SEQ_CALIF.NEXTVAL, :OLD.ID_EVALUACION, :OLD.ANIO, :OLD.CALIFICACION, :OLD.OBSERVACION, :OLD.USUARIO, :OLD.FECHA_HORA, 'U' FROM DUAL; END;
The code for the sequence is:
CREATE SEQUENCE "EVALUACION"."SEQ_CALIF"
MINVALUE 1
MAXVALUE 999999999999999999999999999
INCREMENT BY 1
START WITH 11114992
CACHE 20
NOORDER
NOCYCLE
NOPARTITION;

insert multiple row into table using select however table has primery key in oracle SQL [duplicate]

This question already has answers here:
How to create id with AUTO_INCREMENT on Oracle?
(18 answers)
Closed 8 years ago.
I am facing issue while inserting multiple row in one go into table because column id has primary key and its created based on sequence.
for ex:
create table test (
iD number primary key,
name varchar2(10)
);
insert into test values (123, 'xxx');
insert into test values (124, 'yyy');
insert into test values (125, 'xxx');
insert into test values (126, 'xxx');
The following statement creates a constraint violoation error:
insert into test
(
select (SELECT MAX (id) + 1 FROM test) as id,
name from test
where name='xxx'
);
This query should insert 3 rows in table test (having name=xxx).
You're saying that your query inserts rows with primary key ID based on a sequence. Yet, in your insert/select there is select (SELECT MAX (id) + 1 FROM test) as id, which clearly is not based on sequence. It may be the case that you are not using the term "sequence" in the usual, Oracle way.
Anyway, there are two options for you ...
Create a sequence, e.g. seq_test_id with the starting value of select max(id) from test and use it (i.e. seq_test_id.nextval) in your query instead of the select max(id)+1 from test.
Fix the actual subselect to nvl((select max(id) from test),0)+rownum instead of (select max(id)+1 from test).
Please note, however, that the option 2 (as well as your original solution) will cause you huge troubles whenever your code runs in multiple concurrent database sessions. So, option 1 is strongly recommended.
Use
insert into test (
select (SELECT MAX (id) FROM test) + rownum as id,
name from test
where name='xxx'
);
as a workaround.
Of course, you should be using sequences for integer-primary keys.
If you want to insert an ID/Primary Key value generated by a sequence you should use the sequence instead of selecting the max(ID)+1.
Usually this is done using a trigger on your table wich is executed for each row. See sample below:
CREATE TABLE "MY_TABLE"
(
"MY_ID" NUMBER(10,0) CONSTRAINT PK_MY_TABLE PRIMARY KEY ,
"MY_COLUMN" VARCHAR2(100)
);
/
CREATE SEQUENCE "S_MY_TABLE"
MINVALUE 1 MAXVALUE 999999999999999999999999999
INCREMENT BY 1 START WITH 10 NOCACHE ORDER NOCYCLE NOPARTITION ;
/
CREATE OR REPLACE TRIGGER "T_MY_TABLE"
BEFORE INSERT
ON
MY_TABLE
REFERENCING OLD AS OLDEST NEW AS NEWEST
FOR EACH ROW
WHEN (NEWEST.MY_ID IS NULL)
DECLARE
IDNOW NUMBER;
BEGIN
SELECT S_MY_TABLE.NEXTVAL INTO IDNOW FROM DUAL;
:NEWEST.MY_ID := IDNOW;
END;
/
ALTER TRIGGER "T_MY_TABLE" ENABLE;
/
insert into MY_TABLE (MY_COLUMN) values ('DATA1');
insert into MY_TABLE (MY_COLUMN) values ('DATA2');
insert into MY_TABLE (MY_ID, MY_COLUMN) values (S_MY_TABLE.NEXTVAL, 'DATA3');
insert into MY_TABLE (MY_ID, MY_COLUMN) values (S_MY_TABLE.NEXTVAL, 'DATA4');
insert into MY_TABLE (MY_COLUMN) values ('DATA5');
/
select * from MY_TABLE;

Trigger required to insert data [duplicate]

This question already has answers here:
Using sequential values for the primary key in an INSERT query
(2 answers)
Closed 9 years ago.
I am trying to load a column with unique sequence number each time a row of data is insrerted in the table.How can this be achieved?
You can create a Sequence, and then use the sequence nextval in your insert statements for the column which you want to have sequential incremented value.
CREATE SEQUENCE seq
INCREMENT BY 1
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;
INSERT INTO tab VALUES (seq.nextval, col1, col2, col3);
there is nothing like "auto_increment" or "identity" in Oracle,
but if you want auto increment in your column value you can use Sequence for the this.
after creating sequence you can use After Insert Trigger to insert identical value.
here is trigger example...
CREATE OR REPLACE TRIGGER dep_ins_trig
BEFORE INSERT ON <table_name>
FOR EACH ROW
BEGIN
SELECT dept_seq.NEXTVAL
INTO :new.id
FROM dual;
END;
/
This is achieved by Trigger and Sequence when you want serialized number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like emp_id) by this way, and value of this column is not much considerable, you can use SYS_GUID() at Table Creation to get Auto Increment like this.
CREATE TABLE <table_name>
(emp_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));
Now your emp_id column will accept "globally unique identifier value".
you can insert value in table by ignoring emp_id column like this.
INSERT INTO <table_name> (name) VALUES ('name value');
So, it will insert unique value to your emp_id Column.

How to generate alphanumeric id in Oracle

In my vb application I want an autogenerated id of alphanumeric characters, like prd100. How can I increment it using Oracle as backend?
Any particular reason it needs to be alphanumeric? If it can just be a number, you can use an Oracle sequence.
But if you want just a random string, you could use the dbms_random function.
select dbms_random.string('U', 20) str from dual;
So you could probably combine these 2 ideas (in the code below, the sequence is called oid_seq):
SELECT dbms_random.string('U', 20) || '_' || to_char(oid_seq.nextval) FROM dual
There are two parts to your question. The first is how to create an alphanumeric key. The second is how to get the generated value.
So the first step is to determine the source of the alpha and the numeric components. In the following example I use the USER function and an Oracle sequence, but you will have your own rules. I put the code to assemble the key in a trigger which is called whenever a row is inserted.
SQL> create table t1 (pk_col varchar2(10) not null, create_date date)
2 /
Table created.
SQL> create or replace trigger t1_bir before insert on t1 for each row
2 declare
3 n pls_integer;
4 begin
5 select my_seq.nextval
6 into n
7 from dual;
8 :new.pk_col := user||trim(to_char(n));
9 end;
10 /
Trigger created.
SQL>
The second step requires using the RETURNING INTO clause to retrieve the generated key. I am using SQL*PLus for this example. I confess to having no idea how to wire this syntax into VB. Sorry.
SQL> var new_pk varchar2(10)
SQL> insert into t1 (create_date)
2 values (sysdate)
3 returning pk_col into :new_pk
4 /
1 row created.
SQL> print new_pk
NEW_PK
--------------------------------
APC61
SQL>
Finally, a word of warning.
Alphanumeric keys are a suspicious construct. They reek of "smart keys" which are, in fact, dumb. A smart key is a value which contains multiple parts. At somepoint you will find yourself wanting to retrieving all rows where the key starts with 'PRD', which means using SUBSTR() or LIKE. Even worse someday the definition of the smart key will change and you will have to cascade a complicated update to your table and its referencing foreign keys. A better ides is to use a surrogate key (number) and have the alphanumeric "key" defined as separate columns with a UNIQUE composite constraint to enforce the business rule.
SQL> create table t1 (id number not null
2 , alpha_bit varchar2(3) not null
3 , numeric_bit number not null
4 , create_date date
5 , constraint t1_pk primary key (id)
6 , constraint t1_uk unique (alpha_bit, numeric_bit)
7 )
8 /
Table created.
SQL>

Resources