如何检查SQL Server约束是否存在?

时间:2013-07-06 10:34:19

标签: sql sql-server sql-server-2008

我有以下内容:

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

我希望能够在删除之前检查是否存在约束。我使用上面的代码,表格的类型为'U'。

我如何修改上面的代码(更改xxxx)以检查是否存在约束?

3 个答案:

答案 0 :(得分:26)

 SELECT
    * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 

或者试试这个

  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' 

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 

答案 1 :(得分:7)

尝试这样的事情

IF OBJECTPROPERTY(OBJECT_ID('constraint_name'), 'IsConstraint') = 1
    ALTER TABLE table_name DROP CONSTRAINT constraint_name

答案 2 :(得分:2)

你可以这样做:

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

BEGIN
....
END
ELSE