23/12/2015
Use of Unique Key Constraint in SQL Server.
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
CREATE DATABASE SQL_DEMO
USE SQL_DEMO
CREATE TABLE tbl_Employee
(
EmpID INT PRIMARY KEY NOT NULL,
EmpName VARCHAR (50) NOT NULL,
EmpEmail VARCHAR(20) ,
EmpMobile VARCHAR(20),
UNIQUE (EmpEmail,EmpMobile)
)
INSERT INTO tbl_Employee (EmpID,EmpName,EmpEmail,EmpMobile) VALUES (1,'Robin','[email protected]','999988888')
INSERT INTO tbl_Employee (EmpID,EmpName,EmpEmail,EmpMobile) VALUES (2,'Ram','[email protected]','5555544444')
INSERT INTO tbl_Employee (EmpID,EmpName,EmpEmail,EmpMobile) VALUES (3,'Remo','[email protected]','5555544444')
INSERT INTO tbl_Employee (EmpID,EmpName,EmpEmail,EmpMobile) VALUES (3,'Remo','[email protected]','5555544444')
When we try to run 4th statement then output with error –
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__tbl_Employee__31EC6D26'. Cannot insert duplicate key in object 'dbo.tbl_Employee'.
The statement has been terminated.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
http://www.aspalgo-edu.in/
C #, jQuery, ASP.NET, ASP.NET MVC, WCF, Visual Studio, MS SQL Server, ASP.NET Project, online tutorial, programming, source code, programming