Monday 18 February 2013

Primary Key, Unique Key Constraints – Clustered Index and Non Clustered Index


You can use the below script to create the Primary Key on the already existing tables. Primary key enforces a uniqueness in the column and created the clustered index as default.
Primary key will not allow NULL values.
1-- Adding the NON NULL constraint
2ALTER TABLE [TableName] 
3ALTER COLUMN PK_ColumnName int NOT NULL
4 
5--Script to add the primary key on the existing table
6ALTER TABLE [TableName]
7ADD CONSTRAINT pk_ConstraintName PRIMARY KEY (PK_ColumnName)
If you want to define or create the non-clustered index on the existing table, you can use the below script. If the data in the column is unique, you can create the Unique Constraint as well.
Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column. Unique Key allows only one NULL Value.
1--script to create non-clustered Index
2create index IX_ColumName on TableName(ColumnName)
3--script to create Unique constraint on the existing table
4ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE(ColumnName)

No comments:

Post a Comment