Technical Article

Rename Foreign Key Constraints

,

DESCRIPTION:

I use this script to enforce/apply a naming standard to foreign key constraints.  System named constraints are semi-random and cause problems when promoting changes between servers.  By enforcing a naming standard for constraints, promoted code should be usable in all environments.

**Updated**

Changed output to colums rather than Print screen

Ordered result by Altered Table Name

Add Column to display Constraint Name Length (SQL Constraint Name max is 128)

Updated to use Information_Schema objects and work with multi-column constraints

**

HOW TO USE:

Use the variables at the top of the code to set any schema/table/column filters.

Copy the column values to a new query window and execute.  The script alone will not make any changes.

WHAT IT DOES:

Column 1 drops the constraints.

Column 2 creates the constraints, disabled.  This is done to ensure the constraint definition is not lost if the data does not meet the constraint requirements.

Column 3 enables the constraint and checks all data in the table.  This step may take some time on a table with lots of data.  If the data complies with the constraint, the constraint will be "trusted" by SQL Server.  If the data is not compliant, this step will fail.  At that point you should fix the data and re-enable the constraint.

**DISCLAIMER

As always, backup your database before using the output of this script; this script is provided "as-is" with no support or guarentee of the results or fitness for production.  Use at your own risk.

**

However, it works very well for me and has solved a number of SQL code deployment problems.  I generally run this script after each promotion, just in case someone has created a new system named constraint.

DECLARE @SchemaName sysname = NULL;
DECLARE @TableName sysname = NULL;
DECLARE @ColumnName sysname = NULL;

WITH ConstraintColumns AS
  (
    SELECT  DISTINCT
            rc.CONSTRAINT_NAME,
            rc.CONSTRAINT_CATALOG,
            rc.CONSTRAINT_SCHEMA,
            rc.TABLE_NAME,
            CONSTRAINT_COLUMNS = STUFF(
                                   ( SELECT     ', ' + kcu.COLUMN_NAME
                                       FROM     INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu
                                       WHERE    kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
                                     FOR XML PATH( '' ), TYPE).value( '.', 'NVARCHAR(MAX)' ), 1, 2, '' )
      FROM  INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS rc
  ),
     Statements AS
  (
    SELECT          SQLDrop = 'IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = ''' + Source.CONSTRAINT_NAME + ''' AND CONSTRAINT_SCHEMA = '''
                              + Source.CONSTRAINT_SCHEMA + ''' AND CONSTRAINT_CATALOG = DB_NAME()) BEGIN ALTER TABLE ' + Source.CONSTRAINT_SCHEMA + '.' + Source.TABLE_NAME + ' DROP CONSTRAINT '
                              + Source.CONSTRAINT_NAME + ' END',
                    SQLAdd = 'ALTER TABLE ' + Source.CONSTRAINT_SCHEMA + '.' + Source.TABLE_NAME + ' WITH NOCHECK ADD CONSTRAINT [FK_' + Source.TABLE_NAME + '_'
                             + REPLACE( Source.CONSTRAINT_COLUMNS, ', ', '' ) + '_' + Referenced.CONSTRAINT_SCHEMA + Referenced.TABLE_NAME + '] FOREIGN KEY(' + Source.CONSTRAINT_COLUMNS + ') REFERENCES ['
                             + Referenced.CONSTRAINT_SCHEMA + '].[' + Referenced.TABLE_NAME + '](' + Referenced.CONSTRAINT_COLUMNS + ');',
                    SQLEnable = 'ALTER TABLE ' + Source.CONSTRAINT_SCHEMA + '.' + Source.TABLE_NAME + ' WITH CHECK CHECK CONSTRAINT [FK_' + Source.TABLE_NAME + '_'
                                + REPLACE( Source.CONSTRAINT_COLUMNS, ', ', '' ) + '_' + Referenced.CONSTRAINT_SCHEMA + Referenced.TABLE_NAME + ']',
                    CurrentConstraintName = Source.CONSTRAINT_NAME,
                    ProposedConstraintName = 'FK_' + Source.TABLE_NAME + '_' + REPLACE( Source.CONSTRAINT_COLUMNS, ', ', '' ) + '_' + Referenced.CONSTRAINT_SCHEMA + Referenced.TABLE_NAME,
                    NumRank = ROW_NUMBER() OVER (ORDER BY Source.CONSTRAINT_SCHEMA, Source.TABLE_NAME)
      FROM          INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC
      INNER JOIN    ConstraintColumns AS Source
        ON Source.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
           AND  Source.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
           AND  Source.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
      INNER JOIN    ConstraintColumns AS Referenced
        ON Referenced.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG
           AND  Referenced.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA
           AND  Referenced.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME
      WHERE         ( Source.TABLE_NAME LIKE '%' + @TableName + '%'
                      OR      Referenced.TABLE_NAME LIKE '%' + @TableName + '%'
                      OR      @TableName IS NULL)
                    AND
                      ( Source.CONSTRAINT_COLUMNS LIKE '%' + @ColumnName + '%'
                        OR    Referenced.CONSTRAINT_COLUMNS LIKE '%' + @ColumnName + '%'
                        OR    @ColumnName IS NULL)
                    AND
                      ( Source.CONSTRAINT_SCHEMA = @SchemaName
                        OR    Referenced.CONSTRAINT_SCHEMA = @SchemaName
                        OR    @SchemaName IS NULL)
  )
  SELECT        Statements.SQLDrop,
                Statements.SQLAdd,
                Statements.SQLEnable,
                Statements.CurrentConstraintName,
                Statements.ProposedConstraintName,
                LenConstraintName = LEN( Statements.ProposedConstraintName )
    FROM        Statements
    WHERE       Statements.CurrentConstraintName <> Statements.ProposedConstraintName
    ORDER BY    Statements.NumRank;

Rate

3.67 (3)

Share

Share

Rate

3.67 (3)