1 --Edit by David @ HeBei University 2018 2 3 USE MrDavid 4 GO 5 6 DROP TABLE IF EXISTS SC 7 DROP TABLE IF EXISTS Student 8 DROP TABLE IF EXISTS Course 9 10 CREATE TABLE Student 11 ( 12 Sno CHAR(9) PRIMARY KEY, /* 列级完整性约束条件,Sno是主码*/ 13 Sname CHAR(20) UNIQUE, /* Sname取唯一值*/ 14 Ssex CHAR(2), 15 Sage SMALLINT, 16 Sdept CHAR(20) 17 ); 18 19 CREATE TABLE Course 20 ( 21 Cno CHAR(4) PRIMARY KEY, 22 Cname CHAR(40), 23 Cpno CHAR(4), 24 Ccredit SMALLINT, 25 FOREIGN KEY (Cpno) REFERENCES Course(Cno) 26 ); 27 28 CREATE TABLE SC 29 ( 30 Sno CHAR(9), 31 Cno CHAR(4), 32 Grade SMALLINT, 33 PRIMARY KEY (Sno,Cno), /* 主码由两个属性构成,必须作为表级完整性进行定义*/ 34 FOREIGN KEY (Sno) REFERENCES Student(Sno), /* 表级完整性约束条件,Sno是外码,被参照表是Student */ 35 FOREIGN KEY (Cno)REFERENCES Course(Cno) /* 表级完整性约束条件, Cno是外码,被参照表是Course*/ 36 ); 37 38 39 INSERT INTO Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215121','李勇','男','CS',20); 40 INSERT INTO Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215122','刘晨','女','CS',19); 41 INSERT INTO Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215123','王敏','女','MA',18); 42 INSERT INTO Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215125','张立','男','IS',19); 43 INSERT INTO Student (Sno,Sname,Ssex,Sdept,Sage) VALUES ('201215128','陈冬','男','IS',20); 44 45 SELECT * FROM Student 46 47 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('1','数据库',NULL,4); 48 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('2','数学',NULL,4); 49 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('3','信息系统',NULL,4); 50 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('4','操作系统',NULL,4); 51 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('5','数据结构',NULL,4); 52 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('6','数据处理',NULL,4); 53 INSERT INTO Course(Cno,Cname,Cpno,Ccredit) VALUES ('7','Pascal语言',NULL,4); 54 55 UPDATE Course SET Cpno = '5' WHERE Cno = '1' 56 UPDATE Course SET Cpno = '1' WHERE Cno = '3' 57 UPDATE Course SET Cpno = '6' WHERE Cno = '4' 58 UPDATE Course SET Cpno = '7' WHERE Cno = '5' 59 UPDATE Course SET Cpno = '6' WHERE Cno = '7' 60 61 SELECT * FROM Course 62 63 INSERT INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','1',92); 64 INSERT INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','2',85); 65 INSERT INTO SC(Sno,Cno,Grade) VALUES ('201215121 ','3',88); 66 INSERT INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','2',90); 67 INSERT INTO SC(Sno,Cno,Grade) VALUES ('201215122 ','3',80); 68 69 SELECT * FROM SC