Combine two columns as the primary key : Primary key « Constraints « SQL Server / T-SQL






Combine two columns as the primary key


1>
2> CREATE TABLE ClassGrades(
3>     ClassID int,
4>     StudentID int,
5>     GradeLetter varchar(2),
6>     Constraint PK_ClassGrades PRIMARY KEY(ClassID, StudentID)
7> )
8> GO
1>
2> INSERT ClassGrades VALUES(1,1,'A')
3> GO

(1 rows affected)
1> INSERT ClassGrades VALUES(1,2,'B-')
2> GO

(1 rows affected)
1> INSERT ClassGrades (ClassID, GradeLetter) VALUES(1,'C-')
2> GO
Msg 515, Level 16, State 2, Server JAVA2S\SQLEXPRESS, Line 1
Cannot insert the value NULL into column 'StudentID', table 'master.dbo.ClassGrades'; column does not allow nulls. INSERT fails.
The statement has been terminated.
1> select * from ClassGrades
2> GO
ClassID     StudentID   GradeLetter
----------- ----------- -----------
          1           1 A
          1           2 B-

(2 rows affected)
1>
2> drop ClassGrades
3> GO
Msg 102, Level 15, State 1, Server JAVA2S\SQLEXPRESS, Line 2
Incorrect syntax near 'ClassGrades'.
1>
2>
           
       








Related examples in the same category

1.Define Primary key in table creation command
2.Specification of the primary key of the employee table as a column-level constraint