10> CREATE TABLE Classes(
11> ClassID int PRIMARY KEY,
12> ClassTitle varchar(50)
13> )
14> GO
1>
2> CREATE TABLE ClassGrades(
3> ClassID int REFERENCES Classes(ClassID)
4> ON UPDATE CASCADE,
5> StudentID int,
6> GradeLetter varchar(2),
7> Constraint PK_ClassGrades
8> PRIMARY KEY(ClassID, StudentID)
9> )
10>
11> INSERT Classes VALUES(1,'SQL')
12> INSERT Classes VALUES(999,'Java')
13> GO
(1 rows affected)
(1 rows affected)
1>
2> INSERT ClassGrades VALUES(1, 1, 'C+')
3>
4> INSERT ClassGrades VALUES(1, 2, 'A+')
5> INSERT ClassGrades VALUES(999, 2, 'A')
6> GO
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2> SELECT * FROM Classes
3> GO
ClassID ClassTitle
----------- --------------------------------------------------
1 SQL
999 Java
(2 rows affected)
1>
2> UPDATE Classes
3> SET ClassID = 998
4> WHERE ClassID = 999
5> GO
(1 rows affected)
1>
2> SELECT * FROM Classes
3> GO
ClassID ClassTitle
----------- --------------------------------------------------
1 SQL
998 Java
(2 rows affected)
1>
2> SELECT CG.StudentID, C.ClassTitle, CG.GradeLetter
3> FROM Classes C, ClassGrades CG
4> WHERE C.ClassID = CG.ClassID
5> GO
StudentID ClassTitle GradeLetter
----------- -------------------------------------------------- -----------
1 SQL C+
2 SQL A+
2 Java A
(3 rows affected)
1>
2> drop table ClassGrades;
3> GO
1>
2> drop table Classes;
3> GO
4.9.One to many |
| 4.9.1. | An one-to-many relation |
| 4.9.2. | Enables the changes in the Classes table to propagate to the ClassGrades table |