Thursday, February 5, 2015

Deleting related rows in two tables

             --DELETING RELATED COLUMNS IN TWO TABLES----

CREATE TABLE DEP_NANDU(
DEPT_ID INT NOT NULL,
DNAME VARCHAR(20)  NOT NULL,
LOCATION VARCHAR(10) NOT NULL,
CONSTRAINT PK_DEP_NANDU PRIMARY KEY (DEPT_ID))

SELECT * FROM DEPT_NANDU

INSERT INTO DEPT_NANDU VALUES(80, 'TRANSPORT', 'DUBAI')

CREATE TABLE EMPLY_NANDU(EMP_ID INT NOT NULL,
ENAME VARCHAR(20) NOT NULL,
SAL INT,
DEPT_ID INT NOT NULL,
DNAME VARCHAR(15) NOT NULL,


SELECT * FROM EMPLY_NANDU

INSERT INTO DEP_NANDU SELECT * FROM DEPT_NANDU
DELETE * FROM DEP_NANDU


                                     ------ADDING CONSTRAINT-----

ALTER TABLE TABLENAME ADD CONSTRAINT PK_TABLENAME PK(CLMN NAME)

ALTER TABLE EMPLY_NANDU ADD CONSTRAINT PK_EMPLY_NANDU PRIMARY KEY(DEPT_ID)

 INSERT INTO EMPLY_NANDU VALUES(106,'SFSG',5000,90,'SALES')

SELECT * FROM DEP_NANDU
SELECT * FROM EMPLY_NANDU
 ALTER TABLE EMPLY_NANDU DROP CONSTRAINT PK_EMPLY_NANDU

                                --ADDING ON DELETE CONSTRAINT----



ALTER TABLE EMPLY_NANDU  ADD CONSTRAINT FK_DEP_NANDU
 FOREIGN KEY(DEPT_ID) REFERENCES DEP_NANDU(DEPT_ID)
ON UPDATE CASCADE
ON DELETE CASCADE


DELETE DEP_NANDU WHERE DEPT_ID=70

No comments:

Post a Comment