top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to check if a Constraint exists in Sql server?

+4 votes
10,595 views
How to check if a Constraint exists in Sql server?
posted Nov 3, 2014 by Khusboo

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

Easiest way to check for the existence of a constraint (and then do something such as drop it if it exists) is to use the OBJECT_ID() function...

IF OBJECT_ID('CK_ConstraintName', 'C') IS NOT NULL 
    ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName

OBJECT_ID can be used without the second parameter ('C' for check constraints only) and that may also work, but if your constraint name matches the name of other objects in the database you may get unexpected results.

IF OBJECT_ID('CK_ConstraintName') IS NOT NULL 
    ALTER TABLE dbo.[tablename] DROP CONSTRAINT CK_ConstraintName

OBJECT_ID can also be used with other "constraints" such as Foreign Key constraints or Primary Key constraints, etc. For best results, always include the appropriate object type as the second parameter for the OBJECT_ID function:

Constraint Object Types:

C = CHECK constraint
D = DEFAULT (constraint or stand-alone)
F = FOREIGN KEY constraint
PK = PRIMARY KEY constraint
R = Rule (old-style, stand-alone)
UQ = UNIQUE constraint

answer Nov 5, 2014 by Amit Kumar Pandey
Similar Questions
+4 votes

how to check if table exist and if it doesnt exist create table in sql server 2008

+2 votes

In a stored procedure, for the same table i want to UPDATE if exists else INSERT data.
How ca this be implemented?

...