SL No generation - oracle

There is a master table name as projects master
In another form if I select project-1 sl no need to generate from project master(21819001). after successful 1 record save, if I select same project-1
sl no need to generate like 21819002, for next 21819003, so on.
Again after 3 record save if I select projects-3 sl should generate like 41819001 so on.
I am using Oracle Forms 10g.

Here's an example of what you might do - create additional table which contains the most recent SL_NO for each project. That number is created with an autonomous transaction function which makes sure that in a multi-user environment you won't get duplicates.
PROJECTS_MASTER table and some sample data:
SQL> create table projects_master
2 (project number primary key);
Table created.
SQL> insert into projects_master
2 select 21819001 from dual union all
3 select 41819001 from dual;
2 rows created.
This table will contain the most recent SL_NO for each project
SQL> create table projects_sl_no
2 (project number constraint fk_prsl references projects_master (project),
3 sl_no number);
Table created.
The function itself; if row for PAR_PROJECT exists, it'll update it. Otherwise, it'll create a brand new row in PROJECTS_SL_NO table.
SQL> create or replace function f_proj_sl_no
2 (par_project in projects_master.project%type)
3 return projects_sl_no.sl_no%type
4 is
5 pragma autonomous_transaction;
6 l_sl_no projects_sl_no.sl_no%type;
7 begin
8 select b.sl_no + 1
9 into l_sl_no
10 from projects_sl_no b
11 where b.project = par_project
12 for update of b.sl_no;
13
14 update projects_sl_no b
15 set b.sl_no = l_sl_no
16 where b.project = par_project;
17
18 commit;
19 return (l_sl_no);
20 exception
21 when no_data_found
22 then
23 lock table projects_sl_no in exclusive mode;
24
25 insert into projects_sl_no (project, sl_no)
26 values (par_project, par_project);
27
28 commit;
29 return (par_project);
30 end f_proj_sl_no;
31 /
Function created.
Testing:
SQL> select f_proj_sl_no(21819001) sl_no from dual;
SL_NO
----------
21819001
SQL> select f_proj_sl_no(21819001) sl_no from dual;
SL_NO
----------
21819002
SQL> select f_proj_sl_no(21819001) sl_no from dual;
SL_NO
----------
21819003
SQL> select f_proj_sl_no(41819001) sl_no from dual;
SL_NO
----------
41819001
SQL> select * from projects_sl_no;
PROJECT SL_NO
---------- ----------
21819001 21819003
41819001 41819001
SQL>
As you use Forms, you could call the F_PROJ_SL_NO function in WHEN-VALIDATE-RECORD trigger, PRE-INSERT, or even create a before insert database trigger if you're inserting into a more complex table than the ones I created for testing purposes. Anyway, that should be a simpler part of the story.

Related

Oracle: constraint preventing insert more than N (variable) rows

I've got a table defining the max number of objects for each customer.
Table_1
id_table_1 numeric primary key
cd_object varchar2(20)
max_number number
Another table stores the object assigned to each customer
Table_2
id_table_2 numeric primary key
cd_customer varchar2(20)
cd_object varchar2(20)
How can I set up a constraint in table_2 in order to prevent more than "max_number" record for each "customer - object" couple?
For example:
Table_1
cd_object / max_number
xxx / 1
yyy / 2
Table_2
insert "customer_1", "xxx" -> OK!
insert "customer_1", "xxx" -> KO!
insert "customer_1", "yyy" -> OK!
insert "customer_1", "yyy" -> OK!
insert "customer_1", "yyy" -> KO!
Thanks in advance for your replies.
This constraint is more complex than a CHECK constraint can handle. One day we hope Oracle will support SQL ASSERTIONS which are constraints of arbitrary complexity.
Meanwhile this can be done (with caution re performance) using materialized views (MVs) and constraints. I blogged about this may years ago: your requirement is very similar to my example 3 there. Applying to your case it would be something like:
create materialized view table_2_mv
build immediate
refresh complete on commit as
select t2.cd_customer, t2.cd_object, t1.max_number, count(*) cnt
from table_2 t2
join table_1 t1 on t1.cd_object = t2.cd_object
group by t2.cd_customer, t2.cd_object, t1.max_number;
alter table table_2_mv
add constraint table_2_mv_chk
check (cnt <= max_number)
deferrable;
Pure trigger-based solutions tend to fail in the real world as when 2 users similtaneously add a record that just takes the count to the maximum, both succeed and when committed leave the table with more rows than the maximum in it!
However, taking into account your comment that you have 2M rows in table_2, which perhaps makes the MV approach above unusable, there could be another approach that does involve triggers:
Create a table that denormalizes information from table_1 and table_2 like this:
create table denorm as
select t2.cd_customer, t2.cd_object, t1.max_number, count(*) cnt
from table_2 t2
join table_1 t1 on t1.cd_object = t2.cd_object
group by t2.cd_customer, t2.cd_object, t1.max_number;
Use a trigger or triggers on table_1 to ensure denorm.max_number is always correct - e.g when table_1.max_number is updated to a new value, update the corresponding denorm table rows.
Use a trigger or triggers on table_2 to update the denorm.cnt value - e.g. when a row is added, increment denorm.cnt, when a row is deleted, decrement it.
Add a check constraint to denorm
alter table denorm
add constraint denorm_chk
check (cnt <= max_number);
This is essentially the same as the MV solution, but avoids the full refresh by using triggers to maintain the denorm table as you go along. It works in a multi-user system because the updates to the denorm table serialize changes to table_2 so that 2 users cannot modify it simultaneously and break the rules.
You can use the trigger on TABLE_2 as following:
-- creating the tables
SQL> CREATE TABLE TABLE_1 (
2 ID_TABLE_1 NUMBER PRIMARY KEY,
3 CD_OBJECT VARCHAR2(20),
4 MAX_NUMBER NUMBER
5 );
Table created.
SQL> CREATE TABLE TABLE_2 (
2 ID_TABLE_2 NUMBER PRIMARY KEY,
3 CD_CUSTOMER VARCHAR2(20),
4 CD_OBJECT VARCHAR2(20)
5 );
Table created.
-- creating the trigger
SQL> CREATE OR REPLACE TRIGGER TRG_TABLE_2_MAX_OBJECT BEFORE
2 INSERT OR UPDATE ON TABLE_2
3 FOR EACH ROW
4 DECLARE
5 LV_MAX_NUMBER TABLE_1.MAX_NUMBER%TYPE;
6 LV_COUNT NUMBER;
7 BEGIN
8 BEGIN
9 SELECT
10 MAX_NUMBER
11 INTO LV_MAX_NUMBER
12 FROM
13 TABLE_1
14 WHERE
15 CD_OBJECT = :NEW.CD_OBJECT;
16
17 EXCEPTION
18 WHEN OTHERS THEN
19 LV_MAX_NUMBER := -1;
20 END;
21
22 SELECT
23 COUNT(1)
24 INTO LV_COUNT
25 FROM
26 TABLE_2
27 WHERE
28 CD_OBJECT = :NEW.CD_OBJECT;
29
30 IF LV_MAX_NUMBER = LV_COUNT AND LV_MAX_NUMBER >= 0 THEN
31 RAISE_APPLICATION_ERROR(-20000, 'Not allowed - KO');
32 END IF;
33
34 END;
35 /
Trigger created.
-- testing the code
SQL> INSERT INTO TABLE_1 VALUES (1,'xxx',1);
1 row created.
SQL> INSERT INTO TABLE_1 VALUES (2,'yyy',2);
1 row created.
SQL> INSERT INTO TABLE_2 VALUES (1,'customer_1','xxx');
1 row created.
SQL> INSERT INTO TABLE_2 VALUES (2,'customer_1','xxx');
INSERT INTO TABLE_2 VALUES (2,'customer_1','xxx')
*
ERROR at line 1:
ORA-20000: Not allowed - KO
ORA-06512: at "TEJASH.TRG_TABLE_2_MAX_OBJECT", line 28
ORA-04088: error during execution of trigger 'TEJASH.TRG_TABLE_2_MAX_OBJECT'
SQL> INSERT INTO TABLE_2 VALUES (3,'customer_1','yyy');
1 row created.
SQL> INSERT INTO TABLE_2 VALUES (4,'customer_1','yyy');
1 row created.
SQL> INSERT INTO TABLE_2 VALUES (5,'customer_1','yyy');
INSERT INTO TABLE_2 VALUES (5,'customer_1','yyy')
*
ERROR at line 1:
ORA-20000: Not allowed - KO
ORA-06512: at "TEJASH.TRG_TABLE_2_MAX_OBJECT", line 28
ORA-04088: error during execution of trigger 'TEJASH.TRG_TABLE_2_MAX_OBJECT'
SQL>
-- Checking the data in the TABLE_2
SQL> SELECT * FROM TABLE_2;
ID_TABLE_2 CD_CUSTOMER CD_OBJECT
---------- -------------------- --------------------
1 customer_1 xxx
3 customer_1 yyy
4 customer_1 yyy
SQL>
Cheers!!

How to create a unique id for an existing table in PL SQL?

The situation is that, when I import a file into the database, one of the first thing I usually do is to assign an unique ID for each record.
I normally do below in TSQL
ALTER TABLE MyTable
ADD ID INT IDENTITY(1,1)
I am wondering if there is something similar in PL SQL?
All my search result come back with multiple steps.
Then I'd like to know what PL SQL programmer typically do to ID records after importing a file. Do they do that?
The main purpose for me to ID these records is to trace it back after manipulation/copying.
Again, I understand there is solution there, my further question is whether PL SQL programmer actually do that, or there is other alternative which making this step not necessary in PL SQL?
OK then, as you're on Oracle 11g, there's no identity column there so - back to multiple steps. Here's an example:
I'm creating a table that simulates your imported table:
SQL> create table tab_import as
2 select ename, job, sal
3 from emp
4 where deptno = 10;
Table created.
Add the ID column:
SQL> alter table tab_import add id number;
Table altered.
Create a sequence which will be used to populate the ID column:
SQL> create sequence seq_imp;
Sequence created.
Update current rows:
SQL> update tab_import set
2 id = seq_imp.nextval;
3 rows updated.
Create a trigger which will take care about future inserts (if any):
SQL> create or replace trigger trg_bi_imp
2 before insert on tab_import
3 for each row
4 begin
5 :new.id := seq_imp.nextval;
6 end;
7 /
Trigger created.
Check what's in the table at the moment:
SQL> select * from tab_import;
ENAME JOB SAL ID
---------- --------- ---------- ----------
CLARK MANAGER 2450 1
KING PRESIDENT 5000 2
MILLER CLERK 1300 3
Let's import some more rows:
SQL> insert into tab_import (ename, job, sal)
2 select ename, job, sal
3 from emp
4 where deptno = 20;
3 rows created.
The trigger had silently populated the ID column:
SQL> select * From tab_import;
ENAME JOB SAL ID
---------- --------- ---------- ----------
CLARK MANAGER 2450 1
KING PRESIDENT 5000 2
MILLER CLERK 1300 3
SMITH CLERK 800 4
JONES MANAGER 2975 5
FORD ANALYST 3000 6
6 rows selected.
SQL>
Shortly: you need to
alter table and add the ID column
create a sequence
create a trigger
The end.
The answer given by #Littlefoot would be my recommendation too - but still I thought I could mention the following variant which will work only if you do not intend to add more rows to the table later.
ALTER TABLE MyTable add id number(38,0);
update MyTable set id = rownum;
commit;
My test:
SQL> create table tst as select * from all_tables;
Table created.
SQL> alter table tst add id number(38,0);
Table altered.
SQL> update tst set id = rownum;
3815 rows updated.
SQL> alter table tst add constraint tstPk primary key (id);
Table altered.
SQL>
SQL> select id from tst where id < 15;
ID
----------
1
2
3
4
5
6
7
8
9
10
11
ID
----------
12
13
14
14 rows selected.
But as mentioned initially,- this only fixes numbering for the rows you have at the time of the update - your'e not going to get new id values for new rows anytime later - if you need that, go for the sequence solution.
You can add an id column to a table with a single statement (Oracle 11g, see dbfiddle):
alter table test_
add id raw( 16 ) default sys_guid() ;
Example:
-- create a table without an id column
create table test_ ( str )
as
select dbms_random.string( 'x', 16 )
from dual
connect by level <= 10 ;
select * from test_ ;
STR
ULWL9EXFG6CIO72Z
QOM0W1R9IJ2ZD3DW
YQWAP4HZNQ57C2UH
EETF2AXD4ZKNIBBF
W9SECJYDER793MQW
alter table test_
add id raw( 16 ) default sys_guid() ;
select * from test_ ;
STR ID
ULWL9EXFG6CIO72Z 0x782C6EBCAE2D7B9FE050A00A02005D65
QOM0W1R9IJ2ZD3DW 0x782C6EBCAE2E7B9FE050A00A02005D65
YQWAP4HZNQ57C2UH 0x782C6EBCAE2F7B9FE050A00A02005D65
EETF2AXD4ZKNIBBF 0x782C6EBCAE307B9FE050A00A02005D65
W9SECJYDER793MQW 0x782C6EBCAE317B9FE050A00A02005D65
Testing
-- Are the id values unique and not null? Yes.
alter table test_
add constraint pkey_test_ primary key ( id ) ;
-- When we insert more rows, will the id be generated? Yes.
begin
for i in 1 .. 100
loop
insert into test_ (str) values ( 'str' || to_char( i ) ) ;
end loop ;
end ;
/
select * from test_ order by id desc ;
-- last 10 rows of the result
STR ID
str100 0x782C806E16A5E998E050A00A02005D81
str99 0x782C806E16A4E998E050A00A02005D81
str98 0x782C806E16A3E998E050A00A02005D81
str97 0x782C806E16A2E998E050A00A02005D81
str96 0x782C806E16A1E998E050A00A02005D81
str95 0x782C806E16A0E998E050A00A02005D81
str94 0x782C806E169FE998E050A00A02005D81
str93 0x782C806E169EE998E050A00A02005D81
str92 0x782C806E169DE998E050A00A02005D81
str91 0x782C806E169CE998E050A00A02005D81
Regarding your other questions:
{1} Then I'd like to know what PL SQL programmer typically do to ID records after importing a file. Do they do that? The main purpose for me to ID these records is to trace it back after manipulation/copying.
-> As you know, the purpose of an id is: to identify a row. We don't "do anything to IDs". Thus, your usage of IDs seems legit.
{2} Again, I understand there is solution there, my further question is whether PL SQL programmer actually do that, or there is other alternative which making this step not necessary in PL SQL?
-> Not quite sure what you are asking here. Although there is a ROWID() pseudocolumn (see documentation), we should not use it to identify rows.
"You should not use ROWID as the primary key of a table. If you delete
and reinsert a row with the Import and Export utilities, for example,
then its rowid may change. If you delete a row, then Oracle may
reassign its rowid to a new row inserted later."

Oracle join nextval from sequence

Let's assume
Table TARGET {
ID IDENTITY ...,
...
JOB_NO NUMBER
}
My question is, how can I generate the JOB_NO (by means of a sequence) so that all inserts that have been committed in a statement have the same job_no.
The output should be something like for the n-th execution of that insert stmt.
ID ... JOB_NO
1 ... 123
2 ... 123
3 ... 123
The following is obviously not working. But what is the correct Oracle syntax?
INSERT INTO TARGET SELECT A.*, B.* FROM my_source_table A, (SELECT x.nextval from dual) B
Thanks a lot
Juergen
You could once select the NEXTVAL for every such insert, which increments the sequence and then use CURRVAL within the INSERT.
Let's say this is your sequence
create sequence seq START WITH 123 ;
Always specify the column names in the INSERT to avoid confusion, don't use select * from
select seq.NEXTVAL FROM DUAL;
INSERT INTO TARGET(JOB_NO,col1,col2,..)
SELECT seq.CURRVAL, a.col1,a.col2 FROM my_source_table A, ..
You should be able to do something like:
insert into target select my_seq.nextval, a.* from source a;
Update based on comment below:
SQL*Plus: Release 12.1.0.2.0 Production on Wed Apr 11 12:48:21 2018
Copyright (c) 1982, 2014, Oracle. All rights reserved.
Connected to:
Oracle Database 12c Standard Edition Release 12.1.0.2.0 - 64bit Production
With the Automatic Storage Management option
SQL> create table a(id number, name varchar2(10));
Table created.
SQL> insert into a values(1,'Larry');
1 row created.
SQL> c/1/2
1* insert into a values(2,'Larry')
SQL> c/Larry/Moe
1* insert into a values(2,'Moe')
SQL> /
1 row created.
SQL> c/2/3
1* insert into a values(3,'Moe')
SQL> c/Moe/Curly
1* insert into a values(3,'Curly')
SQL> /
1 row created.
SQL> commit;
Commit complete.
SQL> select * from a;
ID NAME
---------- ----------
1 Larry
2 Moe
3 Curly
SQL> create table b as select 1 id, a.id id_a, a.name from a where 1=0;
Table created.
SQL> desc b
Name Null? Type
----------------------------------------- -------- ----------------------------
ID NUMBER
ID_A NUMBER
NAME VARCHAR2(10)
SQL> create sequence seq_a;
Sequence created.
SQL> insert into b select seq_a.nextval, a.* from a;
3 rows created.
SQL> select * from b;
ID ID_A NAME
---------- ---------- ----------
1 1 Larry
2 2 Moe
3 3 Curly

Oracle views with no affect of underlying table structure changes

I need to create a view over a table and would not wish to change view each time table structure changes. Is there any such possibility? any pointers appreciated around this.
If you don't want to specify all the fields of your table, you can define a view with something like select *, even if I don't like such solution, but you always have to rebuild your view after a table alter.
For example:
SQL> create table yourTable ( a number, b number);
Table created.
SQL> insert into yourTable values ( 1, 2);
1 row created.
SQL> insert into yourTable values ( 10, 20);
1 row created.
SQL> create or replace view yourView as select * from yourTable;
View created.
The view works fine:
SQL> select * from yourView;
A B
---------- ----------
1 2
10 20
If you add a column, the view will not show it:
SQL> alter table yourTable add (c number);
Table altered.
SQL> select * from yourView;
A B
---------- ----------
1 2
10 20
You need to rebuild your view to have the new column:
SQL> create or replace view yourView as select * from yourTable;
View created.
SQL> select * from yourView;
A B C
---------- ---------- ----------
1 2
10 20
If you drop a column, your view will become invalid, and you need to rebuild it:
SQL> alter table yourTable drop column c;
Table altered.
SQL> select * from yourView;
select * from yourView
*
ERROR at line 1:
ORA-04063: view "ALEK.YOURVIEW" has errors
SQL> create or replace view yourView as select * from yourTable;
View created.
SQL> select * from yourView;
A B
---------- ----------
1 2
10 20

Auto Increment for Oracle

I need to create a sequence and a trigger to auto-increment the primary key on a table but I have no idea on how to do it.
Create the table and the sequence
SQL> create table staff (
2 emp_id number primary key,
3 staff_name varchar2(100)
4 );
Table created.
SQL> create sequence emp_id_seq;
Sequence created.
Now, you can create a trigger that uses the sequence to populate the primary key
SQL> create trigger trg_emp_id
2 before insert on staff
3 for each row
4 begin
5 select emp_id_seq.nextval
6 into :new.emp_id
7 from dual;
8 end;
9 /
Trigger created.
Now, when you insert data, you woon't need to specify the EMP_ID column-- it will automatically be populated by the trigger
SQL> insert into staff( staff_name ) values ('Justin');
1 row created.
SQL> select * from staff;
EMP_ID STAFF_NAME
---------- --------------------
1 Justin
Read this, Beautiful article.
how sequence [auto increment in oracle]
syntax
Create sequence sequence_name
start with value
increment by value
minvalue value
maxvalue value;
example
SQL> create table emp (
emp_id number(10),
fname varchar2(25),
lname varchar2(25),
constraint pk_emp_id PRIMARY KEY(emp_id)
);
SQL> Create sequence emp_sequence
start with 1
increment by 1
minvalue 1
maxvalue 10000;
SQL> insert into emp (emp_id,fname,lname) values(emp_sequence.nextval,'Darvin','Johnson');
SQL> insert into emp (emp_id,fname,lname) values(emp_sequence.nextval,'Mig','Andrews');
SQL> insert into emp (emp_id,fname,lname) values(emp_sequence.nextval,'Alex','Martin');
SQL> insert into emp (emp_id,fname,lname) values(emp_sequence.nextval,'Jon','paul');
SQL> insert into emp (emp_id,fname,lname) values(emp_sequence.nextval,'Yatin','Bones');
in emp_sequence.nextval where emp_sequence is the name of sequence we created above and nextval is a function that is used to assign the next number from emp_sequence to emp_id column in emp table.
SQL> select * from emp;
EMP_ID FNAME LNAME
---------- ------------------------- -------------------------
1 Darvin Johnson
2 Mig Andrews
3 Alex Martin
4 Jon paul
5 Yatin Bones
Try this:
create sequence seq_EmpID start with 1 increment by 1
insert into Emp_Table values(seq_EmpID.nextval,'Ram')
I am not sure which version of Oracle you are using, but the following will work in 19c:
create table staff (
emp_id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY PRIMARY KEY,
staff_name varchar2(100)
);
https://docs.oracle.com/en/database/other-databases/nosql-database/19.3/java-driver-table/creating-tables-identity-column.html
The command above creates a system sequence that is automatically employed to populate the key value. you cannot drop the sequence created as it is a system sequence, but because of the dependency on the column when the table is dropped and the recycle bin purged it is removed.
Very good question!!
Probably sequence can be used in this way - also, I am not sure if there really is a difference :
CREATE SEQUENCE emp_id_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 10;
First creating the table :
sql-> create table item(id int primary key, name varchar(25),qty int, price int);
Now we want to make auto increment sequence to the first column i.e. id
sql-> CREATE SEQUENCE id MINVALUE 1 START WITH 1 CACHE 10; //system saves the last 10 items in temp memory
This will create auto increment.
Now we are inserting data:
sql-> insert into item VALUES(id.nextval,'ddcd',2,4);
sql-> insert into item VALUES(id.nextval,'ddcd',676,4);
Finally Displaying the table :
SQL> select * from item;
ID NAME QTY PRICE
1 ddcd 2 4
2 ddcd 676 4
If you use a sequence for several tables, because the value of the sequence is inconsistent example:
we have two tables emp and depeartement:
If I use the sequence on emp I would have: ID_dept = 6 because the 5 is already used in the other table.
example :
SQL> insert into emp values(masequence.nextval,'aaa');
1 ligne crÚÚe.
SQL> insert into departement values(masequence.nextval,'aaa');
1 ligne crÚÚe.
SQL> select * from emp;
ID_EMP NOM_EMP
---------- -------------------------
5 aaa
SQL> select * from departement;
ID_DEPT NOM_DEPT
---------- ----------
6 aaa
SQL>

Resources