11

I have the following:

IF OBJECT_ID(N'[dbo].[webpages_Roles_UserProfiles_Target]', 'xxxxx') IS NOT NULL
   DROP CONSTRAINT [dbo].[webpages_Roles_UserProfiles_Target]

I want to be able to check if there is a constraint existing before I drop it. I use the code above with a type of 'U' for tables.

How could I modify the code above (change the xxxx) to make it check for the existence of the constraint ?

4

3 回答 3

27
 SELECT
    * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 

or else try this

  SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT' 

or

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))
 BEGIN 
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 
于 2013-07-06T10:41:50.820 回答
8

Try something like this

IF OBJECTPROPERTY(OBJECT_ID('constraint_name'), 'IsConstraint') = 1
    ALTER TABLE table_name DROP CONSTRAINT constraint_name
于 2013-07-06T11:16:08.623 回答
4

you can do something like :

IF EXISTS
     (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CONSTRAINT_NAME]') 
      AND type in  (N'U'))

BEGIN
....
END
ELSE
于 2013-07-06T10:43:59.440 回答