Dynamically Naming the Constraint

Introduction

A constraint is nothing but a condition placed on the column or object. Let's see a small example of creating a Primary Key constraint.

CREATE TABLE SANTHOSH_TABLE (NAME VARCHAR(100),ID INT PRIMARY KEY,DOB DATETIME)

---- INSERT RECORDS INTO THE TABLE ----------
INSERT INTO SANTHOSH_TABLE VALUES('VENKAT',1,'1/1/2010')
INSERT INTO SANTHOSH_TABLE VALUES('LINGAM',2,'1/1/2009')
INSERT INTO SANTHOSH_TABLE VALUES('ILAM',3,'1/2/2010')
INSERT INTO SANTHOSH_TABLE VALUES('SANTHOSH',4,'1/3/2010')
INSERT INTO SANTHOSH_TABLE VALUES('SIVARAM',5,'1/4/2010')

SELECT * FROM SANTHOSH_TABLE

dynamically.gif

The Primary key constraint name is PK__SANTHOSH__3214EC2762AFA012 which looks tough to remember the name. SQL Server automatically generates this name. Can we change it to a specific name for the Constraint?

The following query will drop (delete) the constraint located in the table.

--------- DROP CONSTRAINT ON THE TABLE
ALTER TABLE SANTHOSH_TABLE DROP CONSTRAINT PK__SANTHOSH__3214EC2762AFA012

Now, let's see how to name a constraint.

---- DROPPING THE TABLE------------
DROP TABLE SANTHOSH_TABLE
---- NAMING THE CONSTRAINTS EXPLICITLY------------
CREATE TABLE SANTHOSH_TABLE (NAME VARCHAR(100),ID INT ,DOB DATETIME,
CONSTRAINT PK_ID_SANTHOSH PRIMARY KEY (ID))

Summary

This article taught us about Dynamically Naming the Constraint in SQL Server. I hope you like this article.


Similar Articles