adding a sequence to an existing table - oracle

i created a table but i forgot to add a sequence to one of the PK, its a sequence on a form page, i just cant find anything about it, is it possible or do i have to do the form all over again.
i tried to replace the PK but it doesnt give me the option to add the sequence when creating a new one.
i searched everywhere and asked the support in chat (didn't really help since its not their job).
all i could find was this and this.

I'd suggest you to skip Apex in this matter and do the following: presume this is your table:
SQL> create table test
2 (id number constraint pk_test primary key,
3 name varchar2(20)
4 );
Table created.
This is the sequence:
SQL> create sequence myseq;
Sequence created.
As you forgot to specify PK source while creating Apex Form page, never mind - let the database handle it. How? Create a BEFORE INSERT trigger:
SQL> create or replace trigger trg_bi_test
2 before insert on test
3 for each row
4 when (new.id is null)
5 begin
6 :new.id := myseq.nextval;
7 end trg_bi_test;
8 /
Trigger created.
Let's test it: I'm inserting only the NAME (which is what your Apex Form will be doing):
SQL> insert into test (name) values ('Littlefoot');
1 row created.
What is table's contents?
SQL> select * from test;
ID NAME
---------- --------------------
1 Littlefoot
SQL>
See? Trigger automatically inserted ID (primary key) column value.
If it were an Interactive Grid (which lets you insert several records at a time):
SQL> insert into test (name)
2 select 'Bigfoot' from dual union all
3 select 'FAD' from dual;
2 rows created.
SQL> select * from test;
ID NAME
---------- --------------------
1 Littlefoot
2 Bigfoot
3 FAD
SQL>
Works just fine.
And what's another benefit: you don't have to modify Apex application at all.

Related

Update trigger to ensure matching values in other table Oracle SQL Developer

I am trying to come up with a way to make sure that when a table is updated, that a certain condition is met. Can this be done in a trigger? I have made the following two tables, storeTable and employeeTable.
I need to make sure that when storeManager is updated in the storeTable, that the employee has a storeID that matches the store in which I am trying to update the storeManager. (employee cannot be manager of a store he does not work at)
In addition, I need to make sure that the employee exists in the employeeTable. I was thinking some sort of CASE statement would be best, but dont know how this could be enforced by a trigger.
I was thinking about morphing the "Foreign Key Trigger for Child Table" trigger example from https://docs.oracle.com/cd/B12037_01/appdev.101/b10795/adfns_tr.htm#1007172 but I could not figure out how to change this to fit my specific need. Any help is much appreciated.
For context, the current keys are:
storeTable:
storeID PRIMARY KEY
employeeTable:
empID PRIMARY KEY
storeID FOREIGN KEY REFERS TO storeTable.storeID
To me, it seems that constraints can do the job. You don't need triggers.
Here's how. First, create tables without any constraints. Then add them, both primary and foreign key ones which will be deferrable (otherwise you wouldn't be able to insert any rows as parent keys don't exist yet).
SQL> create table employee
2 (empid number,
3 fname varchar2(10),
4 storeid number
5 );
Table created.
SQL> create table store
2 (storeid number,
3 storename varchar2(20),
4 storemanager number
5 );
Table created.
SQL>
SQL> alter table employee add constraint pk_employee primary key (empid, storeid);
Table altered.
SQL> alter table store add constraint pk_store primary key (storeid);
Table altered.
SQL>
SQL> alter table store add constraint fk_store_emp foreign key (storemanager, storeid)
2 references employee (empid, storeid)
3 deferrable initially deferred;
Table altered.
SQL> alter table employee add constraint fk_emp_store foreign key (storeid)
2 references store (storeid)
3 deferrable initially deferred;
Table altered.
SQL>
Now let's add some data: initial insert into employee will be OK until I commit - then it'll fail because its store doesn't exist yet:
SQL> insert into employee values (1, 'John' , 1);
1 row created.
SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (SCOTT.FK_EMP_STORE) violated - parent key not
found
SQL>
But, if I don't commit and pay attention to what I'm entering (i.e. that referential integrity is maintained), it'll be OK:
SQL> insert into employee values (1, 'John' , 1);
1 row created.
SQL> insert into employee values (2, 'Matt' , 2);
1 row created.
SQL> insert into store values (1, 'Santa Clara', 1);
1 row created.
SQL> insert into store values (2, 'San Francisco', 2); --> note 2 as STOREID
1 row created.
SQL> commit;
Commit complete.
SQL> select * From employee;
EMPID FNAME STOREID
---------- ---------- ----------
1 John 1
2 Matt 2
SQL> select * From store;
STOREID STORENAME STOREMANAGER
---------- -------------------- ------------
1 Santa Clara 1
2 San Francisco 2
SQL>
See? So far so good.
Now I'll try to modify STORE table and set its manager to John who works in storeid = 1 which means that it should fail:
SQL> update store set storemanager = 1
2 where storeid = 2;
1 row updated.
SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (SCOTT.FK_STORE_EMP) violated - parent key not
found
SQL>
As expected.
Let's now add emplyoee ID = 6, Jimmy, who works in storeid = 2 and set him to be manager in San Francisco (storeid = 2):
SQL> insert into employee values (6, 'Jimmy', 2);
1 row created.
SQL> update store set storemanager = 6
2 where storeid = 2;
1 row updated.
SQL> commit;
Commit complete.
SQL>
Yey! It works!
As you can see, no triggers needed.
Note that - if you want to drop any of those tables - you'll fail as they are referenced by each other:
SQL> drop table store;
drop table store
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
SQL> drop table employee;
drop table employee
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
SQL>
It means that you'd first have to drop foreign key constraints, then drop tables:
SQL> alter table employee drop constraint fk_emp_store;
Table altered.
SQL> alter table store drop constraint fk_store_emp;
Table altered.
SQL> drop table store;
Table dropped.
SQL> drop table employee;
Table dropped.
SQL>
That's all, I guess.

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;
/

create trigger to save CONSTRAINTs changes on tables in oracle

I want to create table to save all CONSTRAINTs changes in my oracle database,
so i have created this table(table name , constraint name , date , mode like [insert|update|delete] )
CREATE TABLE CONS
(
C_ID NUMBER NOT NULL
, C_NAME VARCHAR2(50) NOT NULL
, T_NAME VARCHAR2(50) NOT NULL
, EXE_DATE DATE NOT NULL
, MODE VARCHAR2(50) NOT NULL
);
the problem was by insert data,
I was thinking of creating trigger on user_cons_columns after insert or update or delete,
but I found that user_cons_columns is a view and i can't create trigger on it,
so how can I do this work?
or what is the tables that I can create trigger on it to do this???
thanks .......
User_Cons_Columns is metadata view in oracle and you can not use it for monitoring constraint changes.
I think, You can use this metadata view :
SELECT *
FROM ALL_CONSTRAINTS T
It shows which constraint has changed by LAST_CHANGE Column and other data that you can use them.
I don't know if we can create DML TRIGGERs on data dictionary tables in Oracle, but that sounds like a bad idea.
My suggestion to you would be to create a DDL Trigger on the ALTER event
Firstly, as a one time activity, you could store all the available constraints in your CONS table.
Then in your trigger, you could use these conditions to check if a table and column was altered.
if (ora_sysevent = 'ALTER' and
ora_dict_obj_type = 'TABLE')
then alter_column :=
ora_is_alter_column('FOO');
end if;
You could then query the user_cons_columns , ALL_CONSTRAINTS and CONS - whichever you find is relevant to store your data - to find if a new constraint was added or not. If it was indeed added or modified, make an entry into CONS or else update it ( using MERGE statement )
As you said, you can't create that type of a trigger on USER_CONS_COLUMNS:
SQL> create or replace trigger trg_myucc
2 before insert
3 on user_cons_columns
4 begin
5 null;
6 end;
7 /
create or replace trigger trg_myucc
*
ERROR at line 1:
ORA-25001: cannot create this trigger type on this type of view
Why wouldn't we try INSTEAD OF TRIGGER?
SQL> create or replace trigger trg_myucc
2 instead of insert
3 on user_cons_columns
4 for each row
5 begin
6 null;
7 end;
8 /
on user_cons_columns
*
ERROR at line 3:
ORA-01031: insufficient privileges
OK, that won't work either. But, what prevents us on creating a view upon a view, and then create INSTEAD OF trigger on that newly created view?
SQL> create or replace view my_ucc as select * from user_cons_columns;
View created.
SQL> create or replace trigger trg_myucc
2 instead of insert
3 on my_ucc
4 for each row
5 begin
6 null;
7 end;
8 /
Trigger created.
Fine; now you have a way to do what you're supposed to do. More about triggers here.

Oracle SEQUENCE.Currval problem in CodeIgniter

I have a sequence named WCOMP_SEQ in oracle to generate auto increment column ON WCOMP table. When I insert a row to WCOMP table in SQLPlus, the row inserted and I can get the auto increment value using
SELECT WCOMP_SEQ.currval FROM dual
But when I ran insert a row using Database Class in CodeIgniter, the row inserted but when I ran the query above to get auto increment value I got Exception:
Exception: Undefined Index currval in E:...
How to fix this?
There is a way to get the value automatically assigned to a column: it is the RETURNING clause.
So, here is my sequence:
SQL> select emp_seq.currval from dual
2 /
CURRVAL
----------
8140
SQL>
I'm going to use it in an INSERT statement:
SQL> var seqval number
SQL> insert into emp
2 (empno, ename, deptno, sal, job)
3 values
4 (emp_seq.nextval, 'JELLEMA', 50, 4575, 'PAINTER')
5 returning empno into :seqval
6 /
1 row created.
SQL>
I returned the EMPNO into a SQL*Plus variable which I can print, and it has the same value as CURRVAL:
SQL> print :seqval
SEQVAL
----------
8141
SQL> select emp_seq.currval from dual
2 /
CURRVAL
----------
8141
SQL>
Your next question is, "does CodeIgniter support the RETURNING sysntax?" I have no idea, but I suspect it does not. Most non-Oracle frameworks don't.
There is always the option to wrap the INSERT statement in a stored procedure, but that's an architectural decision whoch many people dislike.
You can not fetch the SEQUENCE current value without issuing NEXTVAL (see here). So, if you do not want to increment the sequence value (by using NEXTVAL), you should instead query USER_SEQUENCES.
Something like this:
select Sequence_Name
, Last_Number
from user_sequences
where sequence_name = 'WCOMP_SEQ'
/
SEQUENCE_NAME LAST_NUMBER
------------- -----------
WCOMP_SEQ 20
Hope this helps.
In order to get currval on the sequence you will need to have at least one reference to the corresponding nextval for the sequence in the current user session. This is what causes it to set the currval value which would belong to the session.
If you are using it outside, it defeats the purpose which value could it return if there were other sessions active.

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