Oracle: Materialized View not refreshed when using a Prebuilt Table - sql

I'm having problems when using the Prebuilt Table option in a MV in Oracle 12. This code works fine:
CREATE TABLE empt
( ename VARCHAR2(20),
empno INTEGER PRIMARY KEY);
CREATE MATERIALIZED VIEW LOG ON empt
WITH SEQUENCE , rowid (empno)
INCLUDING NEW VALUES;
CREATE MATERIALIZED VIEW empt_MV
REFRESH FAST ON COMMIT
WITH ROWID
AS
SELECT count(*) numberofemps
FROM empt ;
INSERT INTO empt VALUES ('A',1);
COMMIT;
SELECT * FROM empt_MV;
Previous Select return, as expected:
NUMBEROFEMPS
------------
1
But, if I use the ON PREBUILT TABLE option, nothing happens. I mean, the MV remains empty:
drop materialized view empt_mv;
drop materialized view log on empt;
drop table empt;
CREATE TABLE empt
( ename VARCHAR2(20),
empno INTEGER PRIMARY KEY);
CREATE MATERIALIZED VIEW LOG ON empt
WITH SEQUENCE , rowid (empno)
INCLUDING NEW VALUES;
CREATE TABLE empt_MV (
numberofemps NUMBER);
CREATE MATERIALIZED VIEW empt_MV
ON PREBUILT TABLE
REFRESH FAST ON COMMIT
WITH ROWID
AS
SELECT count(*) numberofemps
FROM empt ;
INSERT INTO empt VALUES ('A',1);
COMMIT;
SELECT * FROM empt_MV;
Previous Selects returns no rows.
Anyone knows what happens?

You can't use REFRESH FAST if you are employing WITH ROWID - on your prebuilt table. WITH ROWID Clause

This varies greatly by Oracle version.
Use the instructions provided in the relevant documentation, which will show you how to determine the fast refresh capabilities in your particular situation using DBMS_MView.Explain_MView.
12.1: https://docs.oracle.com/database/121/REPLN/repmview.htm#REPLN304

Related

Get table does not exist error, when trying to insert into table from a trigger

I'm attempting to use a trigger to fill values of another table. The trigger watches for insert on table ratings and updates the values of another table, top5restaurants. I haven't figured out how to maintain only the top 5 in top5restaurants, I don't know how to limit a table to a certain number of entries. But right now I can't seem to do anything to top5restaurants from within the trigger.
drop view top_rest;
create view top_rest (rid, rat)
as
(select distinct rid, max(stars)
from rating
group by rid);
drop table top5restaurants;
create table top5restaurants(rid int);
insert into top5restaurants(rid)
select rid from top_rest
where rownum <= 5
order by rat asc;
create or replace trigger top5_trigger
after insert on ratings
for each row
declare top5 top5restaurants%rowtype;
cursor top5_cursor is
select rid from top_rest
where rownum <=5
order by rat;
begin
for record in top5_cursor
loop
fetch top5_cursor into top5;
insert into top5restaurants values(top5);
end loop;
end;
/
--
--
begin
update_reviews('Jade Court','Sarah M.', 4, '08/17/2017');
update_reviews('Shanghai Terrace','Cameron J.', 5, '08/17/2017');
update_reviews('Rangoli','Vivek T.',3,'09/17/2017');
update_reviews('Shanghai Inn','Audrey M.',2,'07/08/2017');
update_reviews('Cumin','Cameron J.', 2, '09/17/2017');
end;
/
select * from top5restaurants;
insert into top5restaurants values(184);
However, the table does exist and I can run queries on it and it returns the data I inserted when I created the table. I can also insert values. Not sure why I get table not found error when using a trigger.
Apart from the difference in table names(answer by Littlefoot) in the trigger and view, You have not used the rowtype collection properly while inserting the data.
you must remove the brackets:
replace
insert into top5restaurants values(top5);
with
insert into top5restaurants values top5;
Cheers!!
You didn't post all tables involved, but - what is obvious, is that view is created as
create view top_rest ... from rating
------
while trigger is created as
after insert on ratings
-------
^
s?
Which one is it? rating or ratings?

Limit inserts to 6 rows per id

I am learning Hibernate creating a basic console app, using Oracle as the back end. I have a table where if a student enters a 7th record he should not be permitted to do so. How do I do this?
Well beside triggers, you can create a materialized view , then a checking constraint on the table.
create materialized view log on test_table;
create materialized view mv_test_table
refresh FAST on COMMIT
ENABLE QUERY REWRITE
as
select id, count(*) cnts
from test_table
group by id;
alter table test_table
add constraint check_userid
check (cnts< 7);
You can also use a simple trigger (on condition that your table has an ID column):
create or replace trigger trg_limit_row
after insert on your_table
for each row
begin
if :new.id >5 then -- assume that you have id in range (0-5) -> 6 rows
execute immediate 'delete from your_table t where t.id = '
|| ':' || 'new_id';
end if;
end;
/

Oracle trigger to prevent inserting the new row upon a condition

I've found few questions addressing the same question but without a better solution.
I need to create an Oracle trigger which will prevent new inserts upon a condition, but silently (without raising an error).
Ex : I need to stop inserting rows with bar='FOO' only. (I can't edit the constraints of the table, can't access the procedure which really does the insertion etc so the trigger is the only option)
Solutions so far confirms that it isn't possible. One promising suggestion was to create an intermediate table, insert key values to that when bar='FOO' and then delete those records from original table once insertion is done, which is not correct I guess.
Any answer will be highly appreciated.
Apparently, it is not possible to use a trigger to stop inserts without raising an exception.
However, if you have access to the schema (and asking about a trigger this is probably ok), you could think about replacing the table with a view and an instead of trigger.
As a minimal mock up for your current table. myrole is just a stand in for the privileges granted on the table:
CREATE ROLE myrole;
CREATE TABLE mytable (
bar VARCHAR2(30)
);
GRANT ALL ON mytable TO myrole;
Now you rename the table and make sure nobody can directly access it anymore, and replace it with a view. This view can be protected by a instead of trigger:
REVOKE ALL ON mytable FROM myrole;
RENAME mytable TO myrealtable;
CREATE OR REPLACE VIEW mytable AS SELECT * FROM myrealtable;
GRANT ALL ON mytable TO myrole;
CREATE OR REPLACE TRIGGER myioftrigger
INSTEAD OF INSERT ON mytable
FOR EACH ROW
BEGIN
IF :new.bar = 'FOO' THEN
NULL;
ELSE
INSERT INTO myrealtable(bar) VALUES (:new.bar);
END IF;
END;
/
So, if somebody is inserting a normal row into the fake view, the data gets inserted into your real table:
INSERT INTO mytable(bar) VALUES('OK');
1 row inserted.
SELECT * FROM mytable;
OK
But if somebody is inserting the magic value 'FOO', the trigger silently swallows it and nothing gets changed in the real table:
INSERT INTO mytable(bar) VALUES('FOO');
1 row inserted.
SELECT * FROM mytable;
OK
Caution: If you want to protect your table from UPDATEs as well, you'd have to add a second trigger for the updates.
One way would be to hide the row. From 12c this is reasonably easy:
create table demo
( id integer primary key
, bar varchar2(10) );
-- This adds a hidden column and registers the table for in-database archiving:
alter table demo row archival;
-- Set the hidden column to '1' when BAR='FOO', else '0':
create or replace trigger demo_hide_foo_trg
before insert or update on demo
for each row
begin
if :new.bar = 'FOO' then
:new.ora_archive_state := '1';
else
:new.ora_archive_state := '0';
end if;
end demo_hide_foo_trg;
/
-- Enable in-database archiving for the session
-- (probably you could set this in a log-on trigger):
alter session set row archival visibility = active;
insert into demo (id, bar) values (1, 'ABC');
insert into demo (id, bar) values (2, 'FOO');
insert into demo (id, bar) values (3, 'XYZ');
commit;
select * from demo;
ID BAR
-------- --------
1 ABC
3 XYZ
-- If you want to see all rows (e.g. to delete hidden rows):
alter session set row archival visibility = all;
In earlier versions of Oracle, you could achieve the same thing using a security policy.
Another way might be to add a 'required' flag which defaults to 'Y' and set it to to 'N' in a trigger when bar = 'FOO', and (assuming you can't change the application to use a view etc) have a second trigger delete all such rows (or perhaps better, move them to an archive table).
create table demo
( id integer primary key
, bar varchar2(10) );
alter table demo add required_yn varchar2(1) default on null 'Y';
create or replace trigger demo_set_not_required_trg
before insert or update on demo
for each row
begin
if :new.bar = 'FOO' then
:new.required_yn := 'N';
end if;
end demo_hide_foo_trg;
/
create or replace trigger demo_delete_not_required_trg
after insert or update on demo
begin
delete demo where required_yn = 'N';
end demo_delete_not_required_trg;
/

Create a global temporary table in Oracle SQL

I am new to SQL. I want to create a (global or not) temporary table in Oracle SQL which will include a simple selection of data of the form SELECT * FROM tbl_NAME WHERE... and which after the end of my session will be deleted (just like the MSFT SQL temporary tables of the form ##tbl_NAME).
I found online that one way to do it is:
CREATE GLOBAL TEMPORARY TABLE tmp_table
SELECT * FROM tbl_NAME WHERE conditions.
ON COMMIT PRESERVE ROWS;
although I get the error ORA-00904: invalid identifier
I also found that another alternative is
CREATE PRIVATE TEMPORARY TABLE tmp_table AS
SELECT * FROM tbl_NAME WHERE conditions;
which gives the error ORA-00905: missing keyword.
Please note that I already know that one alternative that works is:
DROP TABLE tmp_table;
CREATE TABLE tmp_table AS
SELECT * FROM tbl_NAME;
DROP TABLE tmp_table;
What you want to do with rows comes first; SELECT comes next:
SQL> create global temporary table gtt_dept
2 on commit preserve rows --> first
3 as
4 select * from dept; --> next
Table created.
SQL>
The below format you had shown works in TERADATA
CREATE GLOBAL TEMPORARY TABLE tmp_table
SELECT * FROM tbl_NAME WHERE conditions.
ON COMMIT PRESERVE ROWS;
In Oracle it works like this
create global temporary table gtt_dept
on commit preserve rows
as
select * from dept;

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.