|
You may want a column to receive a unique value
for each of its records.
To specify that a column will require unique
values, when creating it in SQL, use the UNIQUE keyword.
|
Here is an example:
USE Exercise;
GO
CREATE TABLE Students
(
StudentNumber int UNIQUE,
FirstName nvarchar(50),
LastName nvarchar(50) NOT NULL
);
GO
When a column has been marked as unique, during data entry,
the user must provide a unique value for each new record created. If an existing
value is assigned to the column, this would produce an error:
USE Exercise;
GO
CREATE TABLE Students
(
StudentNumber int UNIQUE,
FirstName nvarchar(50),
LastName nvarchar(50) NOT NULL
);
GO
INSERT INTO Students
VALUES(24880, N'John', N'Scheels'),
(92846, N'Rénée', N'Almonds'),
(47196, N'Peter', N'Sansen'),
(92846, N'Daly', N'Camara'),
(36904, N'Peter', N'Sansen');
GO
By the time the fourth record is entered, since it uses a
student number that exists already, the database engine would produce an error:
Msg 2627, Level 14, State 1, Line 2
Violation of UNIQUE KEY constraint 'UQ__Students__DD81BF6C145C0A3F'.
Cannot insert duplicate key in object 'dbo.Students'.
The statement has been terminated.