WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

后端 未结 7 1019
天涯浪人
天涯浪人 2020-12-02 06:06

I\'m looking at the AdventureWorks sample database for SQL Server 2008, and I see in their creation scripts that they tend to use the following:

ALTER TABLE          


        
相关标签:
7条回答
  • 2020-12-02 07:07

    Here is some code I wrote to help us identify and correct untrusted CONSTRAINTs in a DATABASE. It generates the code to fix each issue.

        ;WITH Untrusted (ConstraintType, ConstraintName, ConstraintTable, ParentTable, IsDisabled, IsNotForReplication, IsNotTrusted, RowIndex) AS
    (
        SELECT 
            'Untrusted FOREIGN KEY' AS FKType
            , fk.name AS FKName
            , OBJECT_NAME( fk.parent_object_id) AS FKTableName
            , OBJECT_NAME( fk.referenced_object_id) AS PKTableName 
            , fk.is_disabled
            , fk.is_not_for_replication
            , fk.is_not_trusted
            , ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( fk.parent_object_id), OBJECT_NAME( fk.referenced_object_id), fk.name) AS RowIndex
        FROM 
            sys.foreign_keys fk 
        WHERE 
            is_ms_shipped = 0 
            AND fk.is_not_trusted = 1       
    
        UNION ALL
    
        SELECT 
            'Untrusted CHECK' AS KType
            , cc.name AS CKName
            , OBJECT_NAME( cc.parent_object_id) AS CKTableName
            , NULL AS ParentTable
            , cc.is_disabled
            , cc.is_not_for_replication
            , cc.is_not_trusted
            , ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( cc.parent_object_id), cc.name) AS RowIndex
        FROM 
            sys.check_constraints cc 
        WHERE 
            cc.is_ms_shipped = 0
            AND cc.is_not_trusted = 1
    
    )
    SELECT 
        u.ConstraintType
        , u.ConstraintName
        , u.ConstraintTable
        , u.ParentTable
        , u.IsDisabled
        , u.IsNotForReplication
        , u.IsNotTrusted
        , u.RowIndex
        , 'RAISERROR( ''Now CHECKing {%i of %i)--> %s ON TABLE %s'', 0, 1' 
            + ', ' + CAST( u.RowIndex AS VARCHAR(64))
            + ', ' + CAST( x.CommandCount AS VARCHAR(64))
            + ', ' + '''' + QUOTENAME( u.ConstraintName) + '''' 
            + ', ' + '''' + QUOTENAME( u.ConstraintTable) + '''' 
            + ') WITH NOWAIT;'
        + 'ALTER TABLE ' + QUOTENAME( u.ConstraintTable) + ' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME( u.ConstraintName) + ';' AS FIX_SQL
    FROM Untrusted u
    CROSS APPLY (SELECT COUNT(*) AS CommandCount FROM Untrusted WHERE ConstraintType = u.ConstraintType) x
    ORDER BY ConstraintType, ConstraintTable, ParentTable;
    
    0 讨论(0)
提交回复
热议问题