How do I find a default constraint using INFORMATION_SCHEMA?

前端 未结 14 716
猫巷女王i
猫巷女王i 2020-12-04 13:40

I\'m trying to test if a given default constraint exists. I don\'t want to use the sysobjects table, but the more standard INFORMATION_SCHEMA.

I\'ve used this to che

相关标签:
14条回答
  • 2020-12-04 14:37
    WHILE EXISTS( 
        SELECT * FROM  sys.all_columns 
        INNER JOIN sys.tables ST  ON all_columns.object_id = ST.object_id
        INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
        INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
        WHERE 
        schemas.name = 'dbo'
        AND ST.name = 'MyTable'
    )
    BEGIN 
    DECLARE @SQL NVARCHAR(MAX) = N'';
    
    SET @SQL = (  SELECT TOP 1
         'ALTER TABLE ['+  schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
       FROM 
          sys.all_columns
    
             INNER JOIN
          sys.tables ST
             ON all_columns.object_id = ST.object_id
    
             INNER JOIN 
          sys.schemas
             ON ST.schema_id = schemas.schema_id
    
             INNER JOIN
          sys.default_constraints
             ON all_columns.default_object_id = default_constraints.object_id
    
       WHERE 
             schemas.name = 'dbo'
          AND ST.name = 'MyTable'
          )
       PRINT @SQL
       EXECUTE sp_executesql @SQL 
    
       --End if Error 
       IF @@ERROR <> 0 
       BREAK
    END 
    
    0 讨论(0)
  • 2020-12-04 14:40

    There seems to be no Default Constraint names in the Information_Schema views.

    use SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name to find a default constraint by name

    0 讨论(0)
提交回复
热议问题