On Delete Cascade SQL - sql

The code is written as a script and when i run this script second time, is doesn't drop table EMPLOYEE_TBL because of which various errors are occuring.
Now the question is: Why doesn't DROP TABLE EMPLOYEE_TBL WORK?
DROP TABLE EMPLOYEE_TBL;
DROP TABLE EMPLOYEE_PAY_TBL;
Create table EMPLOYEE_TBL(
EMP_ID VARCHAR(9),
LAST_NAME VARCHAR(15) NOT NULL,
FIRST_NAME VARCHAR(15) NOT NULL,
MIDDLE_NAME VARCHAR(15),
ADDRESS VARCHAR(50) NOT NULL,
CITY VARCHAR(15) NOT NULL,
STATE VARCHAR(10) NOT NULL,
ZIP NUMBER(5) NOT NULL,
PHONE VARCHAR(15),
PAGER VARCHAR(15) );
Alter table EMPLOYEE_TBL
add constraints pk_EMPLOYEE_TBL primary key (EMP_ID);
commit;
Create table EMPLOYEE_PAY_TBL (
EMP_ID VARCHAR(9),
POSITION VARCHAR(15) NOT NULL,
DATE_HIRE DATE,
PAY_RATE DECIMAL(4,2) NOT NULL,
DATE_LAST_RAISE DATE,
Salary Decimal (4, 2),
Bonus Decimal (4, 2) );
--CONSTRAINT EMP_FK FOREIGN KEY (EMP_ID_ REFERENCES
--EMPLOYEE_TBL (EMP_ID));
commit;
Alter table EMPLOYEE_PAY_TBL
add constraints pk_EMPLOYEE_PAY_TBL primary key (EMP_ID);
alter table EMPLOYEE_PAY_TBL
add constraints fk_EMP_ID foreign key (EMP_ID) references EMPLOYEE_TBL (EMP_ID) ON DELETE CASCADE;

The second time, when you try to drop EMPLOYEE_TBL you have this constraint:
alter table EMPLOYEE_PAY_TBL
add constraints fk_EMP_ID foreign key (EMP_ID) references EMPLOYEE_TBL (EMP_ID)
ON DELETE CASCADE;
So you must before remove this constraint and then remove the table.
For further info, please post your error

You can't drop TABLE EMPLOYEE_TBL because it's referenced by EMPLOYEE_PAY_TBL.
The ON DELETE CASCADE option refers to deleting rows in the parent table, not to dropping the parent table.
Judging by the DDL you are most probably using Oracle. In that case you can use the cascade keyword when dropping the table:
DROP TABLE EMPLOYEE_TBL CASCADE CONSTRAINTS;
DROP TABLE EMPLOYEE_PAY_TBL CASCADE CONSTRAINTS;
The CASCADE option for DROP TABLE will automatically alsso drop all foreign keys referencing the table being droppen.

Related

I'm getting an error on Oracle Apex ORA-00907: missing right parenthesis

I'm trying to run this snipped of SQL in Oracle Apex and keep receiving errors about right parenthesis. I have tried to remove the constraints or alter the tables later, but I keep coming up with the same sort of errors. I cannot seem to figure out what it is that's wrong with the table structure, and I can't find anything online about it that makes sense. Any help would be much appreciated, thanks. Code below...
DROP TABLE Employee_T
CASCADE CONSTRAINTS;
DROP TABLE TaxDepartment_T
CASCADE CONSTRAINTS;
DROP TABLE Location_T
CASCADE CONSTRAINTS;
CREATE TABLE Employee_T
(
EmployeeID NUMBER(11) NOT NULL,
EmployeeName VARCHAR2(25) NOT NULL,
EmployeeAddress VARCHAR2(30) ,
EmployeeCity VARCHAR2(20) ,
EmployeeState CHAR(2) ,
EmployeePostalCode VARCHAR2(10) ,
CONSTRAINT Employee_PK PRIMARY KEY(EmployeeID),
CONSTRAINT Employee_FK1 FOREIGN KEY(DepartmentID) REFERENCES (TaxDepartment_T),
CONSTRAINT Employee_FK2 FOREIGN KEY(BranchID) REFERENCES (Location_T)
);
CREATE TABLE TaxDepartment_T
(
DepartmentID INTEGER(11) NOT NULL,
BranchID INTEGER(11) NOT NULL,
CPAID INTEGER(11) NOT NULL,
EmployeeID INTEGER(11) NOT NULL,
BranchName VARCHAR2(50) NOT NULL,
CONSTRAINT TaxDepartment_PK PRIMARY KEY(DepartmentID, BranchID, CPAID),
CONSTRAINT TaxDepartment_FK1 FOREIGN KEY(BranchID) REFERENCES (Location_T),
CONSTRAINT TaxDepartment_FK2 FOREIGN KEY(EmployeeID) REFERENCES (Employee_T)
);
CREATE TABLE Location_T
(
BranchID INTEGER(11) NOT NULL,
BranchName VARCHAR2(50) NOT NULL,
ManagerName VARCHAR2(50) NOT NULL,
EmployeeID INTEGER(11) NOT NULL,
CONSTRAINT Location_PK PRIMARY KEY(BranchID),
CONSTRAINT Location_FK1 FOREIGN KEY(EmployeeID) REFERENCES (Employee_T)
);
Your foreign key constraint syntax is off.
What it should look like:
REFERENCES SCHEMA.TABLE (COLUMN)
and you just have:
REFERENCES (COLUMN)
If you look at this code in SQL Developer, the parser catches your issue right away, and even gives you a simple click to get to the Docs with syntax diagram for defining FK constraints.
This is your FIRST problem.
The fun with bugs is killing one only exposes the next one. You can't create FK constraints for tables you haven't created yet. So either you need to create the base tables first, OR you need to remove the FK constraints from your CREATE TABLE calls, and add them back later as
alter table TABLE_NAME add constraint CONSTRAINT_NAME foreign key(COLUMN_NAME) references TABLE_NAME2(COLUMN_NAME)
Place all of these ALTER TABLE ADD CONSTRAINT calls at the end of your script, once all the tables have already been created.
Someone else has also noticed that you're using INTEGER.
Which I do, ALL THE TIME...because I'm too lazy to type 'NUMBER(38,0)'
That's fine. But what you can't do is say INTEGER(9). That makes no sense in Oracle.
You should use NUMBER instead of INTEGER in TaxDepartment_T and Location_T tables
There are a few syntax issues.
integer is OK but not integer(11). Use number(11). (Also, while char is a valid type, you should stick to the standard varchar2 for strings to avoid unexpected behaviour.)
Foreign key constraints are written constraint fk references tablename, or optionally you can specify the referenced column in brackets: constraint fk references tablename (columnname). (Also if you write them inline as part of the column definition, you can let the datatype inherit from the parent.)
Employee FK1 and FK2 refer to DepartmentID and BranchID columns that the table doesn't have.
You need to put the parent before the child if you want to run it as a script.
I would write it like this:
drop table employee_t cascade constraints;
drop table taxdepartment_t cascade constraints;
drop table location_t cascade constraints;
create table Location_T
( BranchID number(11) not null constraint Location_PK primary key
, BranchName varchar2(50) not null
, ManagerName varchar2(50) not null );
create table TaxDepartment_T
( DepartmentID number(11) not null
, BranchID constraint TaxDepartment_Location_FK references location_t not null
, CPAID number(11) not null
, BranchName varchar2(50) not null
, constraint TaxDepartment_PK primary key(DepartmentID, BranchID, CPAID) );
create table Employee_T
( EmployeeID number(11) not null constraint Employee_PK primary key
, EmployeeName varchar2(25) not null
, EmployeeAddress varchar2(30)
, EmployeeCity varchar2(20)
, EmployeeState varchar2(2)
, EmployeePostalCode varchar2(10)
, DepartmentID constraint Employee_Department_FK references location_t
, BranchID constraint Employee_Branch_FK references Location_T );
I don't think Location or Tax Department should have EmployeeId columns so I removed them - say if you think that's wrong.
Personally I wouldn't put _T on the end of my table names, and I would avoid camelCase naming because the data dictionary doesn't retain it, and so describing a table gives for example:
SQL> #desc location_t
Name Null? Type
----------------------------------------- -------- ----------------------------
BRANCHID NOT NULL NUMBER(11)
BRANCHNAME NOT NULL VARCHAR2(50)
MANAGERNAME NOT NULL VARCHAR2(50)

Oracle PLSQL Cascade Delete doesn't work?

I have some tables with foreign keys which should be deleted. I Put the "on delete cascade" everywhere I needed it, but when I try to Drop the Table i get following error:
*Cause: An attempt was made to drop a table with unique or
primary keys referenced by foreign keys in another table.
This is the Table I want to drop:
DROP TABLE Author;
CREATE TABLE Author (
id NUMBER(4) NOT NULL,
first_name VARCHAR2(30) NOT NULL,
last_name VARCHAR2(30) NOT NULL,
date_of_birth DATE NOT NULL,
date_of_death DATE NULL,
CONSTRAINT Author_PK PRIMARY KEY (id)
);
And this is the Table that is in relation to the Author table:
CREATE TABLE Book (
id NUMBER(4) NOT NULL,
author NUMBER(4) NULL,
title VARCHAR2(30) NOT NULL,
ISBN VARCHAR2(13) NOT NULL,
book_language VARCHAR2(2) NOT NULL,
book_genre VARCHAR2(20) NOT NULL,
CONSTRAINT Book_PK PRIMARY KEY (id),
CONSTRAINT Book_Author FOREIGN KEY (author) REFERENCES Author(id) ON DELETE cascade
);
DROP is a DDL. It has nothing to do with DELETE (DML) (affected by the way you created the foreign key constraint).
Drop child table first; then drop its parent.
I resolved it now with help from #a_horse_with_no_name
If you have the same issue, just write
drop table table_name cascade constraints;

cycles or multiple cascade paths. SQL Error?

I'm trying to create Employee database for practice. I'm getting this error:
Introducing FOREIGN KEY constraint 'fk_dno' on table 'Employee' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints ?
What is causing this error?
create table Department(
Dno int not null,
Name_d varchar(30),
primary key(Dno)
)
create table Employee(
E_id int not null,
F_name varchar(30),
L_name varchar(30),
B_date date,
address_e varchar(30),
salary int,
Sex varchar(8),
Cnic varchar(15),
Email varchar(50),
start_date_e date,
primary key (E_id)
)
alter table Department add Mgr_id int
alter table Department add constraint fk_mgr Foreign key(Mgr_id) references Employee(E_id) on update cascade on delete set null
alter table Employee add Dno int
alter table Employee add constraint fk_dno Foreign key(Dno) references Department(Dno) on update cascade on delete set null
Having mutual foreign keys with ON UPDATE CASCADE creates a cycle because, if you modify a row from one, it searches for rows to delete / modify on the other table, which triggers modification in the other table (the one that originated the change) and so on.
Change the ON UPDATE and ON DELETE options for your FK. Evaluate if you need them mutually referencing fields (you might be designing with the wrong attributes)

can't delete foreign and primary key

can't delete the primary and foreign key, it's simple table but i don't why this error
create table student (
s_ID int ,
S_NAMe varchar2 (10),
S_major varchar2(20),
D_ID number (10) ,
Constraint PK_s_ID primary key (s_ID),
constraint FK_D_ID foreign key (D_ID) references dep (D_ID) );
ALTER TABLE student DROP CONSTRAINT PK_s_ID cascade;
alter table student drop constraint FK_D_ID;
ERROR at line 1:
ORA-02443: Cannot drop constraint - nonexistent constraint
You SQL commands looks correct. You can use following command to make sure constraint exists.
SELECT * FROM user_cons_columns WHERE table_name = 'STUDENT'
If it returns no result, that means you either did not create a constraint or already dropped. You may be trying to re-run the same alter command more than once.

Removing all references from a tuple using Oracle/Access

I created a simple databse using Oracle that has several tables and a few constraints, i am using Access 2007 to interact with the database.
My problem is that I have a table that is called "Customer" which holds several fields, most notably a Primary Key called CUSTID.
I have another table called "Order" which uses the Primary Key in "Customer" as a Foreign Key.
Obviously if i try to delete a customer that is being used in "Order" i get an error as it's being used. This means i have to delete the particular order that references the Customer and then i can delete the Custome record.
I know that "cascade" should delete everything associated with it, my question is how can i do that from Access? I have limited knowledge of databases but enough to create one etc..
This is more of a validation thing, it's just a hassle to delete certain tuples before i can remove another.
This is the database created for Oracle:
--Used to create a "Clean" slate
DROP TABLE ITEM CASCADE CONSTRAINTS;
DROP TABLE CUSTOMER CASCADE CONSTRAINTS;
DROP TABLE CORDER CASCADE CONSTRAINTS;
DROP TABLE FORUM CASCADE CONSTRAINTS;
CREATE TABLE ITEM
(
ITEMID NUMBER(4) NOT NULL,
NAME CHAR(15) NOT NULL,
CATEGORY CHAR(15) NOT NULL,
PRICE NUMBER(8) NOT NULL,
CONSTRAINT ITEM_PK PRIMARY KEY (ITEMID)
);
INSERT INTO ITEM VALUES (1000,'CARROT SEEDS','PACKET SEEDS',2.99);
INSERT INTO ITEM VALUES (2250,'ROSES','FLOWERS',5.99);
INSERT INTO ITEM VALUES (3300,'TOMATOES','PACKET SEEDS',2.99);
INSERT INTO ITEM VALUES (4050,'POTATOES','PACKET SEEDS',1.99);
CREATE TABLE CUSTOMER
(
CUSTID NUMBER(4) NOT NULL,
FNAME CHAR(10) NOT NULL,
LNAME CHAR(10) NOT NULL,
ADDRESS CHAR(40) NOT NULL,
CITY CHAR(15) NOT NULL,
PCODE CHAR(7) NOT NULL,
CNUMBER NUMBER(11) NOT NULL,
CONSTRAINT CUSTOMER_PK PRIMARY KEY (CUSTID)
);
INSERT INTO CUSTOMER VALUES (1010,'JAMIE','KEELING','149 OLD MANSFIELD ROAD','DERBY','DE214SA',07500966490);
INSERT INTO CUSTOMER VALUES (2020,'HELEN','DARLINGTON','27 MOORPARK AVENUE','ROCHDALE','OL113JQ',07890189802);
INSERT INTO CUSTOMER VALUES (3030,'STEVEN','SEGAL','123 FAKE STREET','OHIO','SE095BG',01559345467);
INSERT INTO CUSTOMER VALUES (4040,'BRUCE','WAYNE','17 LAKEVIEW CRESCENT','CHICAGO','MN432BD',07500966490);
CREATE TABLE CORDER
(
ORDERID NUMBER(4) NOT NULL,
CUSTID NUMBER(4) NOT NULL,
SHIPADD CHAR(40) NOT NULL,
SHIPPCODE CHAR(7) NOT NULL,
SHIPDATE DATE,
ITEMID NUMBER(4) NOT NULL,
QUANTITY NUMBER(3) NOT NULL,
TOTAL NUMBER(8) NOT NULL,
CONSTRAINT ORDER_PK PRIMARY KEY (ORDERID),
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID),
CONSTRAINT FK_ITEM FOREIGN KEY (ITEMID) REFERENCES ITEM(ITEMID)
);
INSERT INTO CORDER VALUES (1000,1010,'149 OLD MANSFIELD ROAD','DE214SA','12-JAN-07',1000,100,100.00);
INSERT INTO CORDER VALUES (2000,2020,'27 MOORPARK AVENUE','OL113JQ','04-NOV-10',2250,200,100.00);
INSERT INTO CORDER VALUES (3000,3030,'123 FAKE STREET','SE095BG','30-OCT-08',3300,150,100.00);
INSERT INTO CORDER VALUES (4000,4040,'17 LAKEVIEW CRESCENT','MN432BD','25-JUL-07',4050,125,100.00);
CREATE TABLE FORUM
(
FORUMID NUMBER(4) NOT NULL,
TITLE CHAR(30) NOT NULL,
THREADNAME CHAR(30) NOT NULL,
POSTER CHAR(20) NOT NULL,
POSTDATE DATE,
CONSTRAINT FORUM_PK PRIMARY KEY (FORUMID)
);
INSERT INTO FORUM VALUES (1001,'GENERAL CHAT','BEGINNER QUESTIONS','JAMIE KEELING', '25-NOV-09');
INSERT INTO FORUM VALUES (2002,'OFF TOPIC','FAVOURITE BAND','HELEN DARLINGTON', '12-JAN-09');
INSERT INTO FORUM VALUES (3003,'GENERAL CHAT','WHEN TO HARVEST?','BRUCE WAYNE', '02-NOV-08');
INSERT INTO FORUM VALUES (4004,'OFF TOPIC','WHERE DO YOU LIVE?','STEVEN SEGAL', '13-JAN-08');
Standard SQL way to create foreign key with ON DELETE CASCADE is following. I don't know if Access supports this, but Oracle does have support for ON DELETE CASCADE.
alter table CORDER
add foreign key FK_CUSTOMER
references CUSTOMER(custid)
on delete cascade
If you are re-creating tables, you can also define the foreign keys with on delete cascade in table creation statement. i.e. replace this
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID)
with this
CONSTRAINT FK_CUSTOMER FOREIGN KEY (CUSTID) REFERENCES CUSTOMER(CUSTID) ON DELETE CASCADE