qb icon indicating copy to clipboard operation
qb copied to clipboard

SQL Server constraint checker

Open Daemach opened this issue 4 years ago • 1 comments

The following query will retrieve a list of constraints on a table, including column names, so you can filter if dropping a specific column. When dropping a table you can can then loop over the constraint names and remove the constraints automatically.

I would have done this myself but qb is a lot...

SELECT obj_table.NAME      AS 'table', 
        columns.NAME        AS 'column',
        obj_Constraint.NAME AS 'constraint',
        obj_Constraint.type AS 'type'

    FROM   sys.objects obj_table 
        JOIN sys.objects obj_Constraint 
            ON obj_table.object_id = obj_Constraint.parent_object_id 
        JOIN sys.sysconstraints constraints 
             ON constraints.constid = obj_Constraint.object_id 
        JOIN sys.columns columns 
             ON columns.object_id = obj_table.object_id 
            AND columns.column_id = constraints.colid 
    WHERE obj_table.NAME='your_tablename_here'
    ORDER  BY 'table'

Daemach avatar Apr 18 '20 16:04 Daemach