Error while inserting data in table with Composite primary key - sql

I have table
create table INVOICE
(
brok_dlr_code VARCHAR2(20),
invoice_date DATE,
ba_trxn_date_from DATE,
ba_trxn_date_to DATE,
mf_invoice_no VARCHAR2(40)
);
I created composite primary key
ALTER TABLE BROKER_INVOICE_HISTORY
ADD CONSTRAINT PK_BROKER_INVOICE_HISTORY
PRIMARY KEY(brok_dlr_code, ba_trxn_date_from, ba_trxn_date_to);
there is no record with same brok_dlr_code but executing the script with same ba_trxn_date and ba_trxn_date_to dates but raises error as
ORA-20005: ORA-00001: unique constraint violated

Since there were few records already got inserted, then again running the script cause the script to begin inserting same data. This caused unique constraint violation. Hence old data had to be truncate and re-run the script will not cause this unique constraint.

Related

Mutating table trigger error upon deleting from a table

I have these table definitions
CREATE TABLE EMPLOYEE(
EmployeeID NUMBER(4),
Name VARCHAR2(20),
Hiredate DATE NOT NULL,
Gender VARCHAR(1),
DateOfBirth DATE NOT NULL,
Salary NUMBER(8,2),
Commission NUMBER(8, 2),
DName VARCHAR(20),
PName VARCHAR(20),
Phone NUMBER(8) NOT NULL,
GLetter VARCHAR(1),
CONSTRAINT EMPLOYEE_EMPLOYEEID_PK PRIMARY KEY(EMPLOYEEID),
CONSTRAINT EMPLOYEE_DNAME_FK FOREIGN KEY(DName) REFERENCES DEPARTMENT(DName) ON DELETE CASCADE,
CONSTRAINT EMPLOYEE_PNAME_FK FOREIGN KEY(PName) REFERENCES POSITION(PName) ON DELETE CASCADE,
CONSTRAINT EMPLOYEE_GLETTER_FK FOREIGN KEY(GLetter) REFERENCES GRADE(GLetter) ON DELETE CASCADE,
CONSTRAINT GENDER_CK CHECK (Gender='M' or Gender='F')
);
CREATE TABLE LOGIN(
Username VARCHAR(20),
Password VARCHAR(20),
EmployeeID NUMBER(4),
CONSTRAINT LOGIN_USERNAME_PK PRIMARY KEY(Username),
CONSTRAINT LOGIN_EMPLOYEEID_FK FOREIGN KEY(EmployeeID) REFERENCES EMPLOYEE(EmployeeID) ON DELETE CASCADE
);
CREATE SEQUENCE TRANSACTION_SEQ START WITH 6;
CREATE TABLE TRANSACTION(
TransactionID NUMBER(4) DEFAULT TRANSACTION_SEQ.NEXTVAL,
TransactionDate DATE,
Username VARCHAR(20),
EmployeeID NUMBER(4),
CONSTRAINT TRANSACTION_TRANSACTIONID_PK PRIMARY KEY(TransactionID),
CONSTRAINT TRANSACTION_USERNAME_FK FOREIGN KEY(Username) REFERENCES LOGIN(Username) ON DELETE CASCADE,
CONSTRAINT TRANSACTION_EMPLOYEEID_FK FOREIGN KEY(EmployeeID) REFERENCES EMPLOYEE(EmployeeID) ON DELETE CASCADE
);
and this trigger
CREATE OR REPLACE TRIGGER EMPLOYEE_TRANSACTION
BEFORE INSERT OR UPDATE OR DELETE ON EMPLOYEE
FOR EACH ROW
DECLARE
ID NUMBER(4);
USR VARCHAR(20);
BEGIN
SELECT LOWER(USER)
INTO USR
FROM DUAL;
SELECT EMPLOYEEID
INTO ID
FROM LOGIN
WHERE USERNAME = USR;
INSERT INTO TRANSACTION VALUES(DEFAULT, SYSDATE, USR, ID);
END;
/
my problem arises when trying to delete an employee.
basically, the trigger finds out the employeeid of the user who is making the changes and inserts it and other values to the transaction table. i get this error:
Error report -
ORA-04091: table ---.LOGIN is mutating, trigger/function may not see it
ORA-06512: at "---.EMPLOYEE_TRANSACTION", line 9
ORA-04088: error during execution of trigger '---.EMPLOYEE_TRANSACTION'
is oracle taking into account the possibility that i am deleteing an employee whose id (which is going to be deleted from table LOGIN) is that of the oracle USER?
any solutions? thank you very much!
If we assume that this fiddle is a reproducible test case that demonstrates your problem (note that I had to make several changes to your code in order to be able to do things like inserting the test data), the issue is that the foreign key constraint on the login table is defined to do a cascade delete (on delete cascade). That means that when you are deleting a row from employee, login will be mutating (Oracle is in the middle of deleting the child row). Thus you can't query it from within a trigger on employee.
Depending on exactly what you are hoping to accomplish, you have a few options
Don't query the login table and don't store the employeeID in the transaction table. If you have the username that performed the operation in the transaction table, you can always look up their employeeID.
Don't use triggers to populate the transaction table. If you have a stored procedure that deletes an employee, it makes more sense for that procedure to do the work of logging the transaction.
Don't define your constraints as on delete cascade. That would mean, though, that you'd need to delete the login row prior to deleting the employee row. Here is an example where we remove the on delete cascade from the LOGIN_EMPLOYEEID_FK constraint and add a statement to delete the associated login row.

PostreSql: ERROR: column referenced in foreign key constraint does not exist

What might possibly gone wrong?
ERROR: column "parameter_id" referenced in foreign key constraint does not exist
1 statement failed.
So i created 2 tables(parameters and periods) with the commands;
create table parameters(
parameter_id serial primary key,
temperature real,
feels_good_temperature int,
humidity int,
max_uv_index int
);
and
create table periods(
period_id serial primary key,
time_stamp text
);
...and now i want to have a column, fk_paramter_id in periods table, as a foreign key to the parameters table
I tried achieving it with;
ALTER TABLE periods
ADD CONSTRAINT fk_parameter_id FOREIGN KEY (parameter_id)
REFERENCES parameters(parameter_id);
You first have to create and populate the column:
ALTER TABLE periods ADD parameter_id integer;
Then use UPDATEs to set the correct values.
Now you can define the constraint.
Note: the constraint (fk_paramter_id) is not a column; it is defined on a column (parameter_id).

Nested table primary and foreign key in Oracle

I'm trying to add a primary and foreign key to a nested table, struggling to know how.
This is what I have;
create or replace type profile as object
(
id VARCHAR2(10), --- Suppose to be Primary Key
userID VARCHAR2(10) --- Suppose to be Foreign Key for user table
);
create or replace type profile_nest as table of profile;
CREATE OR REPLACE TYPE user_t UNDER group_T
(profile profile_nest_ty,);
CREATE TABLE user OF user_t
(id NOT NULL,
PRIMARY KEY (id),
nested table profile store as profile_storage_tbl;
Now the problem is this part, trying to do a foreign key -
alter table profile_storage_tbl add CONSTRAINT fk_userID FOREIGN KEY (userID)
REFERENCES user(id);
Gives this error -
*Error starting at line 3 in command:
alter table profile_storage_tbl add CONSTRAINT fk_userID FOREIGN KEY (userID)
REFERENCES user(id)
Error report:
SQL Error: ORA-30730: referential constraint not allowed on nested table column
30730. 00000 - "referential constraint not allowed on nested table column"
*Cause: An attempt was made to define a referential constraint on a nested
table column.
Action: Do not specify referential constraints on nested table columns.
Either you create 2 separate tables profile_storage_tbl and user with a foreign key between them or you create profile_storage_tbl as a nested table within the user table. It doesn't make sense to try to do both. (In fact nested tables make little sense to me, period - but that's another matter!)
It is just as the exception text says, creating a foreign key constraint on nested table columns is not allowed (Oracle 11).
There is sort of a workaround described here: http://ksun-oracle.blogspot.com/2011/05/foreign-key-on-nested-table.html. But there is no guarantee, that this would work on the next oracle release.
Behind the scene oracle will create two tables profile_storage_tbl and user whereas profile_storage_tbl has a foreign key on user.
You can do that on your own, with the advatage to have better control over the releations (also to other tables).

Oracle unique constraint error when inserting

INSERT INTO SS_ALERT_EVENTS ( ALERT_ID, EVENT_ID, TIME_DURATION, ALERT_EVENT_EFFECT, DATASET_ASSIGN_RULE, KEY_FIELDS_ASSIGN_RULE, SIDE, ALERT_VALIDATION_RULE, UNIQUE_ID ) VALUES ( 'test1', 7 , 0, 1 , NULL, '5b414c4552545f494e535452554d454e542e496e737472756d656e742049445d203a3d205b54524144455f5245504f52542e496e737472756d656e742049445d3b', -1, '5b414c4552542e416374696f6e5d203a3d20313b', 1)
*
ERROR at line 1:
ORA-00001: unique constraint (ESV31SURV.PK_SS_ALERT_EVENTS) violated
The EVENT_ID field is the problem. But I want to insert it anyway. However, when I try to drop the constraint of that name, it says there is no such constraint. Further, no such constraint is shown in USER_CONSTRAINTS table. What should I do?
The unique constraint might be in fact be a primary key constraint - at least that's what the name suggests.
Dropping the primary key of a table will potentially have very bad side effect it might break applications that rely on this primary key (and you will also have to drop all foreign keys that reference that table before you can drop the primary key)
That primary key was created with a purposes, so before blindly dropping it you should consult whoever created that schema and make sure that primary key is not needed (or should be redefined).
Having said all this: try to drop the PK using
ALTER TABLE SS_ALERT_EVENTS
DROP PRIMARY KEY
But please double check if this is really a wise decision!

Suggestions for insert with Foreign key constraint in mysql

I have a table containing 2 entries.
Something like
CREATE TABLE `db`.`main` (
`id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
);
The id for these 2 entries are automatically generated primary keys.
I have another table with a rule linking
CREATE TABLE `db`.`day` (
`main_id` int(10) unsigned NOT NULL,
`day` tinyint(4) NOT NULL,
CONSTRAINT `fk_db_main` FOREIGN KEY (`main_id`) REFERENCES `main` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
);
now I can successfully get a result using
SELECT * FROM main where id='9';
but when I try to run
INSERT INTO day (main_id, day) VALUES (9, 0);
I get
"Cannot add or update a child row: a foreign key constraint fails (db.day, CONSTRAINT fk_db_main FOREIGN KEY (main_id) REFERENCES main (id) ON DELETE NO ACTION ON UPDATE NO ACTION) (1452)"
Any suggestions on what I am missing with the insert?
**I hadn't listed the actual cause of the issue while asking the question. The actual cause was that the main db table was in MyISAM, and the InnoDB tables couldn't create a foreign key connecting to it. In short, MyISAM doesn't support foreign keys, even when they are coming from other tables.
The insert works for me if I remove the db. parts in the CREATE TABLE statements (and insert into main a row with an id of 9). Maybe the problem is that you're using that db. prefix inconsistently, i.e. after TABLE but not in the CONSTRAINT clause...?
The FOREIGN KEY constraint says "there shall be an entry in the 'main` table with an ID value that matches the newly inserted 'main_id' value in the 'day' table".
When you INSERT the value 9 into 'day', is there already a row in 'main' with ID = 9?
The DBMS doesn't think so - that's why it complained.
I hadn't listed the actual cause of the issue while asking the question. The actual cause was that the main db table was in MyISAM, and the InnoDB tables couldn't create a foreign key connecting to it. In short, MyISAM doesn't support foreign keys, even when they are coming from other tables.