在sql中删除表

时间:2017-04-08 02:51:00

标签: mysql

嘿所以我对SQL很陌生并且在删除表时遇到问题,到目前为止我的SQL是:

CREATE TABLE COMPANY (
cname       VARCHAR(50)     NOT NULL,
city        VARCHAR(50)     NOT NULL,       
street      VARCHAR(50)     NOT NULL,
bldgnum     DECIMAL(4)      NOT NULL,
email       VARCHAR(320)    NOT NULL,

CONSTRAINT comp_pkey PRIMARY KEY(cname),
CONSTRAINT comp_ckey1 UNIQUE(city, street, bldgnum),
CONSTRAINT comp_ckey2 UNIQUE(email) );


CREATE TABLE DEPARTMENT (
cname       VARCHAR(50)     NOT NULL,
dname       VARCHAR(50)     NOT NULL,

CONSTRAINT dept_pkey PRIMARY KEY(cname, dname),
CONSTRAINT dept_fkey FOREIGN KEY(cname) REFERENCES COMPANY(cname) );


CREATE TABLE EMPLOYEE (
enumber             VARCHAR(50)     NOT NULL,
first_name          VARCHAR(50)     NOT NULL,   
last_name           VARCHAR(50)     NOT NULL,
date_of_brith       DATE                NULL,
salary              DECIMAL(7,2)    NOT NULL,
cname               VARCHAR(50)     NOT NULL,
dname               VARCHAR(50)     NOT NULL,
employee_type       VARCHAR(50)         NULL,
manager_of_cname    VARCHAR(50)         NULL,
manager_of_dname    VARCHAR(50)         NULL,

CONSTRAINT emp_pkey PRIMARY KEY(enumber),
CONSTRAINT emp_fkey FOREIGN(cname, dname) REFERENCES DEPARTMENT(cname, dname),
CONSTRAINT salary CHECK (salary < 0) );


CREATE TABLE PHONE (
pnumber         DECIMAL(10)         NOT NULL,
cname           VARCHAR(50)         NOT NULL,

CONSTRAINT phn_pkey PRIMARY KEY(pnumber),
CONSTRAINT phn_fkey FOREIGN KEY(cname) REFERENCES COMPANY(cname) );

我有一些错误,我相信但我想删除这些表,但得到一个错误说:无法删除或更新父行:外键约束失败。这是我的drop table SQL:

DROP TABLE COMPANY;
DROP TABLE DEPARTMENT;
DROP TABLE EMPLOYEE;
DROP TABLE PHONE;

对于阅读此内容时创建的任何面板表示抱歉,感谢您提供任何帮助,非常感谢。

2 个答案:

答案 0 :(得分:0)

您需要从删除子表开始。这是您的层级:

公司 - &gt;部门 - &gt;雇员

您需要首先删除Employee表,然后删除Department,然后删除Company表。关键是,当该表被另一个表引用时,SQL Server不能删除表。

DROP TABLE EMPLOYEE;
DROP TABLE DEPARTMENT;
DROP TABLE COMPANY;

答案 1 :(得分:0)

在创建员工表时,您错过了外键更改此内容。

Cannot delete or update a parent row: a foreign key constraint fails - &gt;&gt;通过此链接查看解决方案