Triggers in Oracle to keep data integrity - database

I have got a database with stores and rental copies. Each rental copy is assigned to a store. I would like to create a trigger which, if you delete a certain store, it will assign all copies from that store to another , predefined store (cvr).
I have tried like this:
CREATE OR REPLACE TRIGGER delete_trig
BEFORE DELETE ON Store
FOR EACH ROW
BEGIN
UPDATE RentalCopy SET cvr = 123456789
WHERE cvr = :old.cvr;
END;
I get an error which says I have violated a previously added constraint (which takes care of the foreign key between these 2 tables) , as it has found a child record. How can I fix it?
Table definitions for these tables: (relevant part)
RentalCopy:
barcode INTEGER NOT NULL,
CVR INTEGER NOT NULL,
PRIMARY KEY(barcode),
CONSTRAINT fk_storeinfo
FOREIGN KEY (CVR) REFERENCES Store
Store:
CVR INTEGER NOT NULL,
store_name VARCHAR2(30) NOT NULL,
PRIMARY KEY(CVR)

Looking at your code, it seems like your table RentalCopy is connected to Store by a foreign key on the column(s) CVR of both the tables.
So, a CVR value in RentalCopy must have a corresponding cvr on the Store table, failing which you will get a foreign key error.
The error you are getting is possibly because you are trying to delete/update a cvr record from Store
(because then the forign key for the table RentalCopy has no cvr as child in Store table), and not because of any trigger syntax error

Related

Can someone explain this statement (foreign key) of a table

CREATE TABLE genres
(
genre_id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
genre VARCHAR(255) N[enter image description here][1]OT NULL,
parent_id INT NULL,
-- Will be thankful to you for explaining the 3 lines below
PRIMARY KEY (genre_id),
CONSTRAINT fk_parent
FOREIGN KEY(parent_id) REFERENCES genres(genre_id)
);
PRIMARY KEY(genre_id) - means that at most one row in the table GENRES can have a specific value. In other words, for every row in the table, the value in GENRE_ID column will be unique. Additionally the value in the column cannot be null, and that value serves to identify the row uniquely without needing any other value to identify the row. The DDL shows that the database will generate the value for the GENRE_ID column by default.
The "CONSTRAINT fk_parent FOREIGN KEY(parent_id) REFERENCES genres(genre_id) )" means that the database-manger
will enforce that if column PARENT_ID is not null then the value in this column must be an existing value in a row in the GENRES table. Another way of thinking about this is that the database-manager is asked to maintain a parent-child relationship, so a genre may have sub-genres (i.e. a genre may have child genres). So the database manager would not let you specify that a particular genre was a sub-genre of a non-existent parent genre.
The database manager might also enforce the relationship is valid over time, for example it might prevent a delete or update action if that delete would produce orphan rows (i.e. child rows with no parent row) , or it may set such parent_id values to null, depending on the DDL and Db2-version/platform.
Answer:Self Referencing Foriegn Key
https://www.red-gate.com/simple-talk/sql/t-sql-programming/questions-about-primary-and-foreign-keys-you-were-too-shy-to-ask/

Can I use metadata to verify if a Primary Key and a Foreign Key values are valid?

I'm learning SQL and I'm doing some exercises, and I built a procedure that receives as parameters, values that will be inserted into a specific table, once the procedure is executed.
But I need to do some validations. One of the validations is to check if some values are null, because some columns don't accept null values:
IF(#userID IS NULL AND #userPW IS NULL)
I had to remove the identity property from my insert:
SET IDENTITY_INSERT [TABLE] OFF
But now, I need to validate the primary and foreign key parameters.
I was thinking about verifying all rows from the specified table, to check if the value received by parameter is different than any other inserted primary key value.
I would use the same logic for the foreign keys, because I need to check if foreign key received by parameter, is equal to some ID from the referenced table.
But I recently met metadata, which has a lot of functionalities, and I would like to know if I can simplify the validation queries by using metadata.
Thank you.

How can i add a default null in Oracle Database

Hello everyone i am new to databases and i am trying to make add a foreign key the first time i tried i had the following error
ORA-01735: invalid ALTER TABLE option when i googled it it found something like DEFAULT NULL: But when i use it i get the Following error code RA-00904: : invalid identifier
My alter Table looks like this
alter table car
add constraint priceCar DEFAULT NULL foreign key (note) references priceCode(note) DEFAULT NULL;
I dont know what i am doing wrong this is my first time using databases Oracle
Adding the constraint would just be:
alter table car
add constraint priceCar foreign key (note) references priceCode(note);
assuming the relevant column already exists in both tables and is the same data type, and is a primary or unique key in priceCode.
The default value for a column is a completely unrelated issue, and as this is presumably a number column it will default to null anyway. You can explicitly add a default null clause to the column definition (not the constraint) but you don't need to.
Quick demo with made-up tables:
create table pricecode(note number primary key);
Table PRICECODE created.
create table car (id number, note number);
Table CAR created.
alter table car
add constraint priceCar foreign key (note) references priceCode(note);
Table CAR altered.
insert into car (id) values (1);
1 row inserted.
Then:
select * from car;
ID NOTE
---------- ----------
1
shows that note defaulted to null without you having to explicitly set that up (and also that it didn't complain about it not matching any primary key value).

Integrity constraint violation in cakephp

I have created table with Composite Primary Key, but while edit giving Integrity constraint violation error in cakephp.
Integrity constraint violation : 1062 Duplicate entry while saving Composite Primary Key data of model
Integrity constraint violations mean that you are trying to save a duplicate of a Unique value in the database. Primary Keys have to be Unique.
Do you have your Primary Key field in your database set to auto increment? If you do not, that may be your problem.
Otherwise, when you insert a record, it's probably going to insert a row with PK of 0. Then when it tries to insert another record, it will try to insert another row with PK of 0, thus not being unique, and throwing the Integrity Constraint violation.
However
You mentioned that you are doing an edit. If you are doing an edit, then you are not passing the edited rows Primary Key when you are saving it to the database, so cake tries to do a CREATE instead, thus resulting in another duplicate row ID.
Make sure you do this:
$this->Model->id = $id; // Where $id is the Primary Key of the row being edited.
Conversely, you can also do this:
$data['Model']['id'] = $id;
$this->Model->save($data);
You can capture the $id by either storing it as a hidden field in your edit form, or as a URL parameter passed to the action.

SQL Server Conditional Foreign Key Constraints

I'm having trouble figuring out how to create a foreign key constraint. My data model is fixed and out of my control, it looks like this:
CREATE TABLE Enquiry
(Enquiry_Ref INTEGER PRIMARY KEY CLUSTERED, Join_Ref INTEGER, EnquiryDate, EnquiryType...)
CREATE TABLE Contact
(Contact_Ref INTEGER PRIMARY KEY CLUSTERED, Surname, Forenames ....)
CREATE TABLE UniversalJoin
(Join_Ref INTEGER, Contact_Ref INTEGER, Rel_Type INTEGER)
Each Enquiry has exactly one Contact. The link between the two is the UniversalJoin table where
Enquiry.Join_Ref = UniversalJoin.Join_Ref AND
Rel_Type = 1 AND
UniversalJoin.Contact_Ref = Contact.Contact_Ref
The Rel_Type differs depending on what the source table is, so in the case of Enquiry, Rel_Type is 1 but for another table it would set to N.
My question is how do I create a foreign key constraint to enforce the integrity of this relationship? What I want to say, but can't, is:
CREATE TABLE Enquiry
...
CONSTRAINT FK_Foo
FOREIGN KEY (Join_Ref)
REFERENCES UniversalJoin (JoinRef WHERE Rel_Type=1)
You can't use conditional or filtered foreign keys in SQL Server
In these cases, you could have a multiple column FK between (JoinRef, Rel_Type) and set a check constraint on Rel_Type in UniversalJoin to make it 1.
However, I think you are trying to have a row with multiple parents which can't be done.
You might rather want to have a look at CHECK Constraints
CHECK constraints enforce domain
integrity by limiting the values that
are accepted by a column. They are
similar to FOREIGN KEY constraints in
that they control the values that are
put in a column. The difference is in
how they determine which values are
valid: FOREIGN KEY constraints obtain
the list of valid values from another
table, and CHECK constraints determine
the valid values from a logical
expression that is not based on data
in another column.
You could use a table trigger with INSERT and Update to layer the equivalent as a FK.
This way you are able to apply conditions i.e. if column value =1 check exists in table a if column value = 2 then check another table.

Resources