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.
-- Adding the NON NULL constraint ALTER TABLE [TableName] ALTER COLUMN PK_ColumnName int NOT NULL --Script to add the primary key on the existing table ALTER TABLE [TableName] ADD 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.
--script to create non-clustered Index create index IX_ColumName on TableName(ColumnName) --script to create Unique constraint on the existing table ALTER TABLE TableName ADD CONSTRAINT ConstraintName UNIQUE(ColumnName)
Filed under: Database, SQL Server, SQL Server 2008, SQL Server 2008 R2, SQL Server 2011 (Denali) Tagged: Software Development, SQL, SQL Coding Standards, SQL Constraint and Keys, SQL Download, SQL Error Messages, SQL Index, SQL Joins, SQL Performance, SQL Query, SQL Scripts, SQL Security, SQL Server, SQL Tips and Tricks, T-SQL, Technology
