Creating triggers and selecting the sum of shipped order with two variables - sql

I currently have this assignment where we are supposed to create triggers to block the insert of a shipment depending on whether they exceed the total or not.
I have to sum all the shipped quantities and group them by order and product number.
Here are my tables to give an outlook:
My variables are in French, I'm sorry
CREATE TABLE LigneLivraison
(noLivraison NUMBER(19) NOT NULL,
noProduit NUMBER(19) NOT NULL,
noCommande NUMBER(19) NOT NULL,
quantiteLivree NUMBER(19) NOT NULL,
PRIMARY KEY (noLivraison),
FOREIGN KEY (noLivraison) REFERENCES Livraison,
FOREIGN KEY (noProduit) REFERENCES Produit,
FOREIGN KEY (noCommande) REFERENCES Commande
)
/
CREATE TABLE LigneCommande
(noCommande NUMBER(19) NOT NULL,
noProduit NUMBER(19) NOT NULL,
quantite NUMBER(19) NOT NULL,
CHECK (quantite > 0),
PRIMARY KEY (noCommande, noProduit),
FOREIGN KEY (noCommande) REFERENCES Commande,
FOREIGN KEY (noProduit) REFERENCES Produit
)
/
When I try to execute it, Oracle mentions that the SQL command does not end correctly
Here is what I have so far for the first trigger.
CREATE OR REPLACE TRIGGER bloquerInsertionCommande
BEFORE INSERT
ON LigneLivraison
REFERENCING
NEW AS NouvelleLivraison
FOR EACH ROW
BEGIN
SELECT LigneLivraison.noProduit, LigneLivraison.noCommande, LigneCommande.quantite, SUM(LigneLivraison.quantiteLivree) shipped, (LigneCommande.quantite - shipped) Total
FROM LigneLivraison, LigneCommande
WHERE LigneLivraison.noCommande = LigneCommande.noCommande
GROUP BY noCommande AND noProduit;
IF :NouvelleLivraison.quantiteLivree > Total THEN raise_application_error(-20100, 'La quantite a livrer est trop elevee');
END IF;
END;
/
Since shipping can be made seperately and an x number of times, I need to add all the same product of a certain order number to compare it with what the client originally ordered.

Your create table commands are not working as there are multiple issues as mentioned in the comments inline in following code:
CREATE TABLE LigneLivraison
(noLivraison NUMBER(19) NOT NULL,
noProduit NUMBER(19) NOT NULL,
noCommande NUMBER(19) NOT NULL,
quantiteLivree NUMBER(19) NOT NULL,
PRIMARY KEY (noLivraison),
FOREIGN KEY (noLivraison) REFERENCES Livraison(pk_column_name_of_livraison_table), -- you need to add column name of referencing table here
FOREIGN KEY (noProduit) REFERENCES Produit(pk_column_name_of_produit_table), -- you need to add column name of referencing table here
FOREIGN KEY (noCommande) REFERENCES Commande(pk_column_name_of_commande_table) -- you need to add column name of referencing table here
); -- ending statement with ;
-- / -- this is not needed in sql statements
CREATE TABLE LigneCommande
(noCommande NUMBER(19) NOT NULL,
noProduit NUMBER(19) NOT NULL,
quantite NUMBER(19) NOT NULL CHECK (quantite > 0), -- combined it in single column level constraint
PRIMARY KEY (noCommande, noProduit),
FOREIGN KEY (noCommande) REFERENCES Commande(pk_column_name_of_commande_table), -- you need to add column name of referencing table here
FOREIGN KEY (noProduit) REFERENCES Produit(pk_column_name_of_produit_table) -- you need to add column name of referencing table here
);
--/
Also, pk of referencing table is written in comment for clarity. You can use pk or unique key in references clause according to your requirement.
After your tables are created properly then only you will be able to identify proper error in the trigger.

Related

ERROR: violates foreign key constraint, key is not present in parent table (but it is??)

I know this question has been asked many times, but none of the answers have solved my issue.
I am creating a database for a uni assignment, using PostgreSQL through pgadmin 4, and I have a table named "staff" populated with staff members with a primary key of "staffid". I then have another table named "client_international", which includes a foreign key of "staffid" which relates to the staff tables primary key.
When trying to insert into the client table, I am getting the following error:
ERROR: insert or update on table "client_international" violates foreign key constraint "intclient_staff_fkey"
DETAIL: Key (staffid)=(100000024) is not present in table "staff".
SQL state: 23503
I am certain that that '100000024' key is in the staff table.. yet I still get the error. Any suggestions? Below I will paste the code I used to create the staff and client tables, in case anyone notices an error in them.
Staff table:
CREATE SEQUENCE staff_seq
start 100000000
increment 1;
CREATE TABLE staff
(
staffid integer default nextval('staff_seq'),
firstname varchar(20) NOT NULL,
lastname varchar(20) NOT NULL,
"position" varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
"location" integer NOT NULL,
CONSTRAINT staff_pkey PRIMARY KEY (staffid)
);
Client table:
CREATE SEQUENCE client_seq
start 200000000
increment 1;
CREATE TABLE client
(
clientid integer default nextval('client_seq'),
company varchar(100) NOT NULL,
sector varchar(100) NOT NULL,
pointofcontact varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
approvalstatus boolean default (false),
"location" integer NOT NULL,
staffid integer NOT NULL,
CONSTRAINT client_pkey PRIMARY KEY (clientid)
);
CREATE TABLE client_international
(
CONSTRAINT client_international_pkey PRIMARY KEY (clientid)
) INHERITS ("client");
ALTER TABLE client
ADD CONSTRAINT client_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT client_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
ALTER TABLE client_international
ADD CONSTRAINT intclient_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT intclient_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
I get the error when running the following statements:
INSERT INTO client_international(company, sector, pointofcontact, mobile, email, approvalstatus, "location", staffid)
VALUES ('Moores Dogs', 'Border Patrol', 'Carol Moore', '07911 653453', 'jenkinsj#k9solutions.co.uk', 'false', '500000001', '100000024');
Here's a screenshot of the entry in the staff table, showing that it's definitely in there:
Foreign keys aren't "inherited".
Quote from the manual
A serious limitation of the inheritance feature is that [...] foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
(emphasis mine)
So what you are trying to do, simply isn't supported.

Oracle: Constraints of keys

I have an entity within Oracle's SQL:
and I'm wondering, what does "UF" represent? I've written the SQL code but I do not know how to represent the "UF" attribute as a constraint.
CREATE TABLE entry (
entryno NUMBER(4) NOT NULL,
carndate DATE NOT NULL,
entrystarttime DATE NOT NULL,
entryfinishtime DATE NOT NULL,
entryplace NUMBER(4) NOT NULL,
charname VARCHAR2(30) NOT NULL,
compno NUMBER(4) NOT NULL,
eventypecode CHAR(3) NOT NULL,
teamname VARCHAR2(30) NOT NULL
);
ALTER TABLE entry ADD CONSTRAINT entry_pk PRIMARY KEY ( entryno,
carndate );
ALTER TABLE entry
ADD CONSTRAINT entry_charity_fk FOREIGN KEY ( charname )
REFERENCES charity ( charname );
ALTER TABLE entry
ADD CONSTRAINT entry_carnival_fk FOREIGN KEY ( carndate )
REFERENCES carnival ( carndate );
ALTER TABLE entry #
ADD CONSTRAINT entry_competitor_fk FOREIGN KEY ( compno )
REFERENCES competitor ( compno );
ALTER TABLE entry #
ADD CONSTRAINT entry_event_fk FOREIGN KEY ( carndate, eventypecode )
REFERENCES evenet ( carndate, eventypecode );
ALTER TABLE entry
ADD CONSTRAINT entry_team_fk FOREIGN KEY ( teamname, carndate )
REFERENCES team ( teamname,carndate );
ALTER TABLE entry
ADD CONSTRAINT ... ("UF")
The UF is actually two flags.
As you've recognised the F means the column is a foreign key. The U stands for Unique. Those columns form part of the compound unique key:
ALTER TABLE entry ADD CONSTRAINT entry_carnival_un UNIQUE
( carndate, compno, eventypecode );
carndate is also part of the compound primary key so really it should be flagged PFU but I guess the modelling tool didn't allow for three flags.

ORA-01748: only simple column names allowed here in Oracle

What I am trying to do ?
I am trying to create two tables and at the same time i am trying to link them together using foreign and primary keys. However I successfully create my parent table ( Student with primary key ) but failed to create child table ( Attendence with foreign key ).
What is the problem ?
I get the following error while creating Attendence table:
ERROR at line 5: ORA-01748: only simple column names allowed here
My code:
Student table:
create table Student (
ST_ROLLNO NUMBER(6) constraint s_pk primary key,
ST_NAME VARCHAR(30) not null,
ST_ADDRESS varchar(35) not null
);
Attendence table:
create table Attendence (
ST_ROLLNO NUMBER(6),
ST_DATE VARCHAR(30) not null,
ST_PRESENT_ABSENT varchar(1) not null,
constraint f_pk Attendence.ST_ROLLNO foreign key references Student(ST_ROLLNO)
);
Your foreign key constraint syntax is wrong; it should be:
constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
You are preceding the FK column name with the table name, which is wrong in itself, but also have it in the wrong place.
create table Student (
ST_ROLLNO NUMBER(6) constraint s_pk primary key,
ST_NAME VARCHAR(30) not null,
ST_ADDRESS varchar(35) not null
);
Table STUDENT created.
create table Attendence (
ST_ROLLNO NUMBER(6),
ST_DATE VARCHAR(30) not null,
ST_PRESENT_ABSENT varchar(1) not null,
constraint f_pk foreign key (ST_ROLLNO) references Student(ST_ROLLNO)
);
Table ATTENDENCE created.
According to oracle documentation,
ORA ERR
ORA-01748 only simple column names allowed here
The following is the cause of this error:
This SQL statement does not allow a qualified column name, such as
username.table.column or table.column.
Action you can take to resolve this issue: Remove the qualifications
from the column and retry the operation.
In your case, you are trying to refer to the table name while defining a constraint -
Attendence.ST_ROLLNO - WRONG.
It must contain a simple name without the table name or schema name.

correcting errors in sql code

I am new to this website, i hope that i ask the question the right way
-- Create a Database table to represent the "FACT" entity.
CREATE TABLE FACT
(
Time_id DATE NOT NULL,
Area_id INTEGER NOT NULL,
Reported_crime_id INTEGER NOT NULL,
Crime_status VARCHAR(8) NOT NULL,
no_of_crime INTEGER NOT NULL,
Max_crime INTEGER NOT NULL,
Avg_crime INTEGER NOT NULL,
Min_crime INTEGER NOT NULL,
date_reported DATE NOT NULL,
-- Specify the PRIMARY KEY constraint for table "FACT".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_fact PRIMARY KEY (Time_id, Area_id, Reported_crime_id,
Crime_status)
);
-- Create a Database table to represent the "Crime_Dim" entity.
CREATE TABLE Crime_Dim
(
REPORTED_CRIME_ID INTEGER NOT NULL,
CRIME_TYPE_Desc VARCHAR(50),
DATE_REPORTED DATE NOT NULL,
Crime_type_id INTEGER NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Crime_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_crime_dim PRIMARY KEY (REPORTED_CRIME_ID)
);
-- Create a Database table to represent the "Location_Dim" entity.
CREATE TABLE Location_Dim
(
AREA_ID INTEGER NOT NULL,
AREA_Name VARCHAR(30) NOT NULL,
Area_code INTEGER NOT NULL,
Force_id INTEGER NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Location_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_location_dim PRIMARY KEY (AREA_ID)
);
-- Create a Database table to represent the "Time_Dim" entity.
CREATE TABLE Time_Dim
(
Time_id INTEGER NOT NULL,
day_id INTEGER NOT NULL,
Month_id INTEGER NOT NULL,
Year INTEGER,
-- Specify the PRIMARY KEY constraint for table "Time_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_time_dim PRIMARY KEY (Time_id)
);
-- Create a Database table to represent the "Reported_crime_dim" entity.
CREATE TABLE Reported_crime_dim
(
Crime_status VARCHAR(20) NOT NULL,
Date_reported DATE NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Reported_crime_dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_reported_crime_dim PRIMARY KEY (Crime_status)
);
-- i.e. tables may be referenced before they have been created. This method is therefore safer.
-- Alter table to add new constraints required to implement the "FACT_Time_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Time_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk1_fact_to_time_dim FOREIGN KEY(Time_id) REFERENCES Time_Dim(
Time_id) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Location_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Location_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk2_fact_to_location_dim FOREIGN KEY(AREA_ID) REFERENCES
Location_Dim(AREA_ID) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Crime_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Crime_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk3_fact_to_crime_dim FOREIGN KEY(REPORTED_CRIME_ID) REFERENCES
Crime_Dim(REPORTED_CRIME_ID) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Reported_crime_dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Reported_crime_dim"
ALTER TABLE FACT
ADD CONSTRAINT fk4_fact_to_reported_crime_dim FOREIGN KEY(Crime_status)
REFERENCES Reported_crime_dim(Crime_status) ON DELETE RESTRICT ON UPDATE
RESTRICT;
--------------------------------------------------------------
-- End of DDL file auto-generation
--------------------------------------------------------------
​
Could someone help me in correcting the errors in the sql code above? when i run the code as mentioned at the last few codes i need to create constraint to prevent Foreign keys in the Fact table and relate them back to their original table if i have got this right...
could someone correct the code and let me know plz
Following this answer, you have to remove ON DELETE RESTRICT and ON UPDATE RESTRICT.
There's no such option in Oracle.

Sybase constraint with foreign key and conditional check against foreign table column value

Is it possible on Sybase to define a constraint(s) which require a column to be a foreign key and also satisfy a condition based on the value of a foreign column, e.g. in the below example tables could a constraint be created on the "product" table such that "product.code is a foreign key of a brand.code which has valid=1"?
CREATE TABLE brand (
code char(8) NOT NULL,
valid int NOT NULL,
rowid numeric(10,0) IDENTITY,
CONSTRAINT brand_pk PRIMARY KEY (code),
CONSTRAINT valid_check CHECK (valid IN (0,1))
)
CREATE TABLE product (
code char(8) NOT NULL,
CONSTRAINT product_pk PRIMARY KEY (code)
)
I think it's best to change the structure just a little bit.
CREATE TABLE brand (
code char(8) NOT NULL,
valid int NOT NULL,
rowid numeric(10,0) IDENTITY,
CONSTRAINT brand_pk PRIMARY KEY (code),
-- The following UNIQUE constraint lets the pair of values be the target of
-- a foreign key reference.
CONSTRAINT brand_is_valid UNIQUE (code, valid),
CONSTRAINT valid_check CHECK (valid IN (0,1))
);
CREATE TABLE product (
code char(8) NOT NULL,
valid int NOT NULL,
-- The column "code" is a PK in the referenced table, so this still works. It's
-- a 1:0 or 1:1 relationship.
CONSTRAINT product_pk PRIMARY KEY (code),
-- The next constraint requires a unique constraint on the pair of
-- columns in the table "brand". By itself, it references every row
-- in "brand". That's too many rows.
CONSTRAINT product_fk FOREIGN KEY (code, valid)
REFERENCES brand (code, valid),
-- But this constraint restricts the foreign key references to only those
-- rows that have valid = 1 in the table "brand".
CHECK (valid = 1)
);
In order to bypass the creation of a foreign-key based on the "valid" condition, you will need to modify your table design and create a trigger to set the product.code = NULL. Pardon my syntax (I haven't coded Sybase for a while), but this is the general idea:
Add a new column to serve as the primary key since we will need to set product.code = NULL when valid=0:
CREATE TABLE product (
rowid int identity primary key,
code char(8) NULL,
CONSTRAINT brand_fk FOREIGN KEY (code) REFERENCES brand(code)
)
Then create a trigger similar to this one:
create trigger FK_WhenValid
on product
for insert
AS
IF (SELECT COUNT(*) FROM brand b inner join inserted i on b.code = i.code AND b.valid=0 ) > 0
BEGIN
UPDATE product SET code = NULL WHERE code in (SELECT i.code from brand b join inserted i on b.code = i.code and b.valid = 0)
END
Note: this trigger only supports product insertions. If "valid" can change, another approach is required.
You could also implement the foreign key as a trigger instead of a declarative constraint and only set product.code = inserted.code when valid = 1