updating create view - error ORA-01779: - oracle

I've used the CREATE VIEW command to create a view (obviously), and join multiple tables. The CREATE VIEW command works perfectly, but when I try to update the VIEW RentalInfoOct, I receive error "ORA-01779: cannot modify a column which maps to a non key-preserved table"
CREATE VIEW RentalInfoOct
(branch_no, branch_name, customer_no, customer_name, item_no, rental_date)
AS
SELECT i.branchNo, b.branchName, r.customerNo, c.customerName, i.itemNo, r.dateFrom
FROM item i
INNER JOIN rental r
ON i.itemNo = r.itemNo
INNER JOIN branch b
ON i.branchNo = b.branchNo
INNER JOIN customer c
ON r.customerNo = c.customerNo
WHERE r.dateFrom
BETWEEN to_date('10-01-2009','MM-DD-YYYY')
AND to_date('10-31-2009','MM-DD-YYYY')
My update command.
UPDATE RentalInfoOct
SET item_no = '3'
WHERE customer_name = 'April Alister'
AND branch_name = 'Kingsway'
AND rental_date = '10/28/2009'
I'm not sure if this will help in solving the problem, but here are my CREATE TABLE commands
CREATE TABLE Branch
(
branchNo SMALLINT NOT NULL,
branchName VARCHAR(20) NOT NULL,
branchAddress VARCHAR(40) NOT NULL,
PRIMARY KEY (BranchNo)
);
--Item Table Definition
CREATE TABLE Item
(
branchNo SMALLINT NOT NULL,
itemNo SMALLINT NOT NULL,
itemSize VARCHAR(8) NOT NULL,
price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (ItemNo, BranchNo),
FOREIGN KEY (BranchNo) REFERENCES Branch ON DELETE CASCADE,
CONSTRAINT VALIDAMT
CHECK (price > 0)
);
-- Customer Table Definition
CREATE TABLE Customer
(
customerNo SMALLINT NOT NULL,
customerName VARCHAR(15) NOT NULL,
customerAddress VARCHAR(40) NOT NULL,
customerTel VARCHAR(10),
PRIMARY KEY (CustomerNo)
);
-- Rental Table Definition
CREATE TABLE Rental
(
branchNo SMALLINT NOT NULL,
customerNo SMALLINT NOT NULL,
dateFrom DATE NOT NULL,
dateTo DATE,
itemNo SMALLINT NOT NULL,
PRIMARY KEY (BranchNo, CustomerNo, dateFrom),
FOREIGN KEY (BranchNo) REFERENCES Branch(BranchNo) ON DELETE CASCADE,
FOREIGN KEY (CustomerNo) REFERENCES Customer(CustomerNo) ON DELETE CASCADE,
CONSTRAINT CORRECTDATES CHECK (dateTo > dateFrom OR dateTo IS NULL)
);

See: Oracle: multiple table updates => ORA-01779: cannot modify a column which maps to a non key-preserved table
You're attempting to update a view with joins, but the join conditions are not based on a uniqueness constraint, which creates the possibility of multiple rows that are created from a single row in one table.
It seems like you need a Unique Key - Foreign Key relationship between the columns your join condition is based on.
EDIT: I just saw your edit. Changing r.branchNo = b.branchNo to i.branchNo = b.branchNo should go a long way. Not sure how well r.customerNo = c.customerNo will work out.

Related

Do I need to drop a foreign key on one table to delete a row on another using oracle?

I have two tables
Parent table
(account_number varchar(15) not null,
branch_name varchar(50) not null,
balance number not null,
primary key(account_number));
Child table
account_number varchar(15) not null,
foreign key(account_number) references parent table(account_number));
I am trying this:
DELETE FROM parent table
WHERE balances > 1000;
I am deleting accounts by balances on the parent but I get an error message about the child relationship.
My assumption is a DELETE CASCADE has to be added to the foreign key in the child table. All the documentation shows how to alter the table when the constraint is named. I do not have that situation. Is there a way to do it, or do I have to specify the cascade in the delete statement I am writing?
Every constraint in Oracle has a name. If a name isn't specified when the constraint is created, Oracle will autogenerate a name for the constraint. If you don't know what the name of a constraint is, try running a SQL statement that violates the constraint and reading the constraint name from the error message:
SQL> delete from parent where account_number = 1234;
delete from parent where account_number = 1234
*
ERROR at line 1:
ORA-02292: integrity constraint (LUKE.SYS_C007357) violated - child record
found
In this case the name of the constraint is SYS_C007357.
If that doesn't work, you can query the data dictionary view user_constraints:
SQL> select constraint_name from user_constraints where table_name = 'CHILD' and constraint_type = 'R';
CONSTRAINT_NAME
------------------------------
SYS_C007357
As far as I can tell, you can't modify a foreign key constraint to enable ON DELETE CASCADE. Instead you must drop the constraint and recreate it.
I don't believe you can apply the CASCADE option to a DELETE statement either, but you can delete the child rows before deleting from the parent:
DELETE FROM child
WHERE account_number IN (SELECT account_number FROM parent WHERE balance > 1000);
DELETE FROM parent
WHERE balance > 1000;
However, I don't know how many other tables you have with foreign key constraints referencing your parent table, nor in how many places you are deleting from the parent table, so I can't say how much work it would be to use this approach.
yes you can set DELETE CASCADE
see more info here FOREIGN KEYS WITH CASCADE DELETE
CREATE TABLE table_name
(
column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE
);
for example
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);

How do I perform a deletion of table entries from a full outer join?

What I have is several tables...two of them being:
CREATE TABLE Orders(
oid int NOT NULL,
rdate date,
sdate date,
cid int NOT NULL,
eid int NOT NULL,
PRIMARY KEY (oid),
FOREIGN KEY (cid) REFERENCES Customer(cid),
FOREIGN KEY (eid) REFERENCES Employee(eid));
CREATE TABLE PartOrder(
poid int NOT NULL,
pid int NOT NULL,
oid int NOT NULL,
PRIMARY KEY (poid),
FOREIGN KEY (pid) REFERENCES Part(pid),
FOREIGN KEY (oid) REFERENCES Orders(oid));
What I need to do is this:
Create and execute a query that deletes all PartOrder records for Orders for which the shipping date is in the past.
So, I came up with this...
DELETE
FROM (SELECT * FROM PartOrder FULL OUTER JOIN Orders ON partorder.oid=orders.oid)
WHERE sdate<sysdate;
This is giving me this error:
ORA-01752: cannot delete from view without exactly one key-preserved table
Can someone offer me some insight?
I'd write this as something like
DELETE FROM PARTORDER
WHERE POID IN (SELECT p.POID
FROM PARTORDER p
INNER JOIN ORDERS o
ON o.OID = p.OID
WHERE o.SDATE < SYSDATE);
Best of luck.

Employee/History - Part of composite key as foreign key

I've got 2 entities:
1) EMPLOYEES (Parent)
CREATE TABLE EMPLOYEES (
employee_id NUMBER (3) NOT NULL,
first_name VARCHAR (20) NOT NULL,
last_name VARCHAR (20) NOT NULL,
job_title VARCHAR (20) NOT NULL,
employee_type VARCHAR (1) NOT NULL,
salary NUMBER (5),
hourly_pay NUMBER (5,2),
bonus_pay NUMBER (5,2),
CONSTRAINT employee_pk PRIMARY KEY(employee_id));
2) EMPLOYEE_HISTORY (Child)
CREATE TABLE EMPLOYEE_HISTORY (
start_date DATE NOT NULL,
employee_id NUMBER (3) NOT NULL,
end_date DATE,
job_title VARCHAR (10) NOT NULL,
hourly_rate NUMBER (5,2) NOT NULL,
CONSTRAINT employee_history_pk PRIMARY KEY(start_date, employee_id));
I'm trying to create:
ALTER TABLE employee_history
ADD CONSTRAINT employee_history_fk
FOREIGN KEY (employee_id)
REFERENCES employee_history(employee_id);
When I do this, I get an error
ORA-02270: no matching unique or primary key for this column-list
My guess is that I cannot create the constraint on just employee_id because I have a composite key in my child table. I understand when an employee gets put into the database, the parent table is filled out and the "start date" should be filled out along with everything else. However, I do not understand how this would work if I had start_date in my parent table as well. I would be able to create my constraint, yes, but how will I be able to keep a record of changes in start_date if my start_date was inputted at the time of when the employee was entered into the database.I thought about using job_title as a primary key instead of start_date because it's present in both tables, but what happens when an employee gets promoted and demoted again? Won't a duplicate value constraint come up when the same employee_id and job_title is getting inserted?
Your references clause needs to reference the parent table. Not the child table
ALTER TABLE employee_history
ADD CONSTRAINT employee_history_fk
FOREIGN KEY (employee_id)
REFERENCES employee(employee_id); -- employee not employee_history
The SQL you posted is trying to create a self-referential foreign key where employee_history is both the parent and the child. That doesn't make sense in this case.

Why it tell "invalid identifier (ORA-00904)"? when I call function in CONSTRAINT CHECK

This is some kind of study database in sql file. I use oracle 11g and process it in sqlplus.
I wrote two function for check the course number and the department number, so its depend on the major and the minor department of each student.
For example, I am student of CS department (major) and BIO department (minor), so I can not enroll the course which is about math department.
When I call it in CHECK but I don't know why it told that.
This is output when I create all table, (from sqlplus)
....
....
....
table created.
ALTER TABLE sections ADD CONSTRAINT CK_course_depart CHECK (FindMYDeparture(stuid,find_dno_from_cno(cno)) = 'true');
ERROR at line 1:
ORA-0094: "FIND_DNO_FROM_CNO":invalid identifier
This is in .sql file
DROP TABLE department CASCADE CONSTRAINTS;
CREATE TABLE department (
dnumber number(4) not null,
dname varchar(25) not null,
primary key (dnumber)
);
DROP TABLE courses CASCADE CONSTRAINTS;
CREATE TABLE courses (
cno number(4) not null,
cname varchar(15) not null,
credit number(1) not null,
dnumber number(4) not null,
primary key (cno),
foreign key (dnumber) references department(dnumber),
CONSTRAINT credits CHECK (credit > 0 AND credit <= 5)
);
DROP TABLE student CASCADE CONSTRAINTS;
CREATE TABLE student (
stuid char(9) not null,
fname varchar(15) not null,
lname varchar(15) not null,
dMjno number(4) not null,
dMnno number(4),
primary key (stuid),
CONSTRAINT depart_M_n CHECK (dMjno <> dMnno),
CONSTRAINT dMinor_check CHECK (dMnno = 1 OR dMnno = 2 OR dMnno = 3)
);
DROP TABLE sections CASCADE CONSTRAINTS;
CREATE TABLE sections (
sno number(4) not null,
cno number(4) not null,
stuid char(9) not null,
semester varchar(6) not null,
year varchar(4) not null,
instructor varchar(15) not null,
CONSTRAINT combine_pk primary key (sno,stuid),
foreign key (cno) references courses(cno),
foreign key (stuid) references student(stuid),
CONSTRAINT cant_enroll CHECK (semester <> 'Spring' AND year <> 2007)
);
DROP TABLE grading CASCADE CONSTRAINTS;
CREATE TABLE grading (
sno number(4) not null,
stuid char(9) not null,
grade numeric(1,2),
foreign key (sno,stuid) references sections(sno,stuid),
foreign key (stuid) references student(stuid),
CONSTRAINT grading_check CHECK (grade >= 0 AND grade <= 4)
);
DROP FUNCTION FindMYDeparture;
CREATE OR REPLACE FUNCTION FindMYDeparture(stuid_in IN char,depart_course IN NUMBER)
RETURN NUMBER AS
departMa_no NUMBER;
departMi_no NUMBER;
report varchar(10);
CURSOR cdno is
SELECT dMjno,dMnno FROM student WHERE stuid = stuid_in;
BEGIN
OPEN cdno;
LOOP
FETCH cdno INTO departMa_no,departMi_no;
IF (departMa_no = depart_course OR departMi_no = depart_course)
THEN
report := 'true';
EXIT;
ELSE
report := 'flase';
END IF;
EXIT WHEN cdno%NOTFOUND;
END LOOP;
CLOSE cdno;
RETURN report;
END;
/
DROP FUNCTION find_dno_from_cno;
CREATE OR REPLACE FUNCTION find_dno_from_cno(cno_in IN NUMBER)
RETURN NUMBER AS
depart_no NUMBER;
CURSOR cdno is
SELECT dnumber FROM courses WHERE cno = cno_in;
BEGIN
OPEN cdno;
FETCH cdno INTO depart_no;
CLOSE cdno;
RETURN depart_no;
END;
/
ALTER TABLE sections ADD CONSTRAINT CK_course_depart CHECK (FindMYDeparture(stuid,find_dno_from_cno(cno)) = 'true');
Not going to happen. You are not allowed to use your pl/sql functions in check constraint by design:
•Conditions of check constraints cannot contain the following
constructs:
•Subqueries and scalar subquery expressions
•Calls to the functions that are not deterministic (CURRENT_DATE,
CURRENT_TIMESTAMP, DBTIMEZONE, LOCALTIMESTAMP, SESSIONTIMEZONE,
SYSDATE, SYSTIMESTAMP, UID, USER, and USERENV)
•Calls to user-defined functions
•Dereferencing of REF columns (for example, using the DEREF function)
•Nested table columns or attributes
•The pseudocolumns CURRVAL, NEXTVAL, LEVEL, or ROWNUM
•Date constants that are not fully specified
http://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm
Try running every statement in that function, This is the case of non existent column for a table or using a not existing row.

Foreign key data integrity violation on Oracle X 10g

I have an integration test running against either a MySQL instance or an Oracle instance.
The test passes fine when building the Maven project against the MySQL instance.
Here is the table structure:
drop table if exists operator;
create table operator (
id bigint(20) unsigned not null auto_increment,
version int(10) unsigned not null,
name varchar(50),
unique key name (name),
description varchar(255),
operator_id varchar(50),
unique key operator_id (operator_id),
image varchar(255),
url varchar(255),
country_id bigint(20) unsigned not null,
primary key (id),
unique key id (id),
key country_id (country_id),
constraint operator_fk1 foreign key (country_id) references country (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
But when the same test runs against the Oracle instance then it gives me the exception:
1. insert into operator (version, country_id, description, image, name, operator_id, url, id) values (0, 19, 'The SFR operator', 'sfr.jpg', 'SFR', NULL, 'sfr.fr', 10)
java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (NITROPROJECT.OPERATOR_FK1) violated - parent key not found
Here is the table structure:
create table operator (
id number(10) not null,
version number(10) not null,
name varchar2(50),
constraint operator_u1 unique (name),
description varchar2(255),
operator_id varchar2(50),
constraint operator_u2 unique (operator_id),
image varchar2(255),
url varchar2(255),
country_id number(10) not null,
constraint operator_pk primary key (id),
constraint operator_fk1 foreign key (country_id) references country (id)
);
create sequence sq_id_operator increment by 1 start with 1 nomaxvalue nocycle cache 10;
create or replace trigger tr_id_inc_operator
before insert
on operator
for each row
declare
begin
if (:new.id is null)
then
select sq_id_operator.nextval into :new.id from dual;
end if;
end;
/
create table country (
id number(10) not null,
version number(10) not null,
code varchar2(4) not null,
constraint country_u1 unique (code),
name varchar2(50) not null,
list_order number(10),
constraint country_pk primary key (id)
);
create sequence sq_id_country increment by 1 start with 1 nomaxvalue nocycle cache 10;
create index country_i1 on country (list_order, name);
create or replace trigger tr_id_inc_country
before insert
on country
for each row
declare
begin
select sq_id_country.nextval into :new.id from dual;
end;
/
The country is created with the following service:
#Modifying
#Transactional(rollbackFor = EntityAlreadyExistsException.class)
#Override
public Country add(Country country) {
if (findByCode(country.getCode()) == null) {
// Save the returned id into the entity
country = countryRepository.saveAndFlush(country);
return country;
} else {
throw new EntityAlreadyExistsException();
}
}
I can see in the console log that the country is actually created and that its primary key id is returned:
2014-09-19 13:00:05,839 DEBUG [sqlonly] com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
1. insert into country (version, code, list_order, name, id) values (0, 'fr', 1, 'France', 19)
In fact, I also added a finder call to make sure the country could be retrieved after it being created:
countryFR = new Country();
countryFR.setCode("fr");
countryFR.setName("France");
countryFR.setListOrder(1);
Country country = countryService.findByCode(countryFR.getCode());
if (country == null) {
countryFR = countryService.add(countryFR);
} else {
countryFR = country;
}
Country myc = countryService.findById(countryFR.getId());
if (myc != null) {
logger.debug("==============>> Found the country id: " + myc.getId());
}
And the console log does show the logger output:
2014-09-19 13:00:05,854 DEBUG [BTSControllerTest] ==============>> Found the country id: 19
NOTE: The console log does NOT show any select statement corresponding to that findById call.
And then comes the attempt to insert an operator:
1. insert into operator (version, country_id, description, image, name, operator_id, url, id) values (0, 19, 'The SFR operator', 'sfr.jpg', 'SFR', NULL, 'sfr.fr', 10)
You can see that the country id is the same as the one for the inserted country.
To sum things up:
The above note about the absence of select statement makes me wonder if the country was really inserted or not.
The primary key id of 19 retrieved after inserting the country leads me to think the country was actually inserted.
So how come Oracle complains it cannot find it for the operator foreign key ?
I'm using JPA2 hibernate-jpa-2.1-api 1.0.0.Final and spring-data-jpa 1.6.2.RELEASE and hibernate 4.3.6.Final
Here are the connection properties:
jpaPropertiesMap.put("hibernate.dialect", databaseProperties.getHibernateDialect());
jpaPropertiesMap.put("hibernate.show_sql", "true");
jpaPropertiesMap.put("hibernate.format_sql", "true");
jpaPropertiesMap.put("hibernate.hbm2ddl.auto", databaseProperties.getHibernateHbm2ddlAuto());
jpaPropertiesMap.put("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
jpaPropertiesMap.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
jpaPropertiesMap.put("hibernate.c3p0.min_size", "5");
jpaPropertiesMap.put("hibernate.c3p0.max_size", "20");
jpaPropertiesMap.put("hibernate.c3p0.timeout", "1000");
jpaPropertiesMap.put("hibernate.c3p0.max_statements", "50");
EDIT:
I added the following properties to the JPA setup:
jpaPropertiesMap.put("hibernate.connection.autocommit", "true");
jpaPropertiesMap.put("hibernate.cache.use_query_cache", "false");
jpaPropertiesMap.put("hibernate.cache.use_second_level_cache", "false");
But it didn't change anything in the issue.
I found the solution. My sequence trigger was missing an if statement. Now it has one as in: if (:new.id is null)
create or replace trigger tr_id_inc_country
before insert
on country
for each row
declare
begin
if (:new.id is null)
then
select sq_id_country.nextval into :new.id from dual;
end if;
end;
/
I suppose Hibernate was getting a sequence number for the insert, and then Oracle was getting another one at commit time. I'm just guessing here.

Resources