错误信息:
服务器: 消息 547,级别 16,状态 1,行 1
INSERT 语句与 COLUMN FOREIGN KEY 约束 'FK__SC__Cno__263B8EAF' 冲突。该冲突发生于数据库 'master',表 'Course', column 'Cno'。
语句已终止。
服务器: 消息 547,级别 16,状态 1,行 1
INSERT 语句与 COLUMN FOREIGN KEY 约束 'FK__SC__Cno__263B8EAF' 冲突。该冲突发生于数据库 'master',表 'Course', column 'Cno'。
语句已终止。
sql语句:
CREATE TABLE Student
(Sno CHAR(9) PRIMARY KEY,
Sname CHAR(20) UNIQUE,
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20)
);
CREATE TABLE Course
(Cno CHAR(4) PRIMARY KEY,
Cname CHAR(40),
Cpno CHAR(4),
Ccredit SMALLINT,
FOREIGN KEY (Cpno) REFERENCES Course(Cno)
);
CREATE TABLE SC
(Sno CHAR(9),
Cno CHAR(4),
Grade SMALLINT,
PRIMARY KEY (Sno,Cno),
FOREIGN KEY (Sno) REFERENCES Student(Sno),
FOREIGN KEY (Cno) REFERENCES Course(Cno)
);
SELECT *
FROM Student;
INSERT
INTO Student(Sno,Sname,Ssex,Sdept,Sage)
VALUES('200215128','陈冬','男','IS',18);
INSERT
INTO Student
VALUES('200215126','张成民','男',18,'CS');
INSERT
INTO SC(Sno,Cno)
VALUES('200215128','1');
INSERT
INTO SC
VALUES('200215126','1',NULL);
数据库 sql
------解决方案--------------------
你都没有插入数据到Course,既然sc和Course有关联,就要先插入Course,然它有可以关联的数据才能插入sc
------解决方案--------------------
因为SC.Cno字段参考Course.Cno字段,此时Course表为空,找不到Course.Cno为1的数据,所以无法插入SC表.
脚本改成这样就可以了.
CREATE TABLE Student
(Sno CHAR(9) PRIMARY KEY,
Sname CHAR(20) UNIQUE,
Ssex CHAR(2),
Sage SMALLINT,
Sdept CHAR(20)
);
CREATE TABLE Course
(Cno CHAR(4) PRIMARY KEY,
Cname CHAR(40),
Cpno CHAR(4),
Ccredit SMALLINT,
FOREIGN KEY (Cpno) REFERENCES Course(Cno)
);
CREATE TABLE SC
(Sno CHAR(9),
Cno CHAR(4),
Grade SMALLINT,
PRIMARY KEY (Sno,Cno),
FOREIGN KEY (Sno) REFERENCES Student(Sno),
FOREIGN KEY (Cno) REFERENCES Course(Cno)
);
INSERT INTO Student(Sno,Sname,Ssex,Sdept,Sage)
VALUES('200215128','陈冬','男','IS',18);
INSERT INTO Student
VALUES('200215126','张成民','男',18,'CS');
-- 插入Cno为1的记录.
insert into Course(Cno,Cname,Cpno,Ccredit)
select '1','Cno1','1',10
INSERT INTO SC(Sno,Cno)
VALUES('200215128','1');
INSERT INTO SC
VALUES('200215126','1',NULL);