16.06.2013

SQL: Drop constraints

Sometimes before dropping the table one has to drop the constraints first. This useful stored procedure can drop the constraints for the selected table fro you:
CREATE PROCEDURE p_DropAllTableConstraints
(
    @TableName nvarchar(255)
)
AS
    DECLARE @sql nvarchar(255)
    WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = DB_NAME() and table_name = @TableName)
    BEGIN
        select  @sql = 'ALTER TABLE ' + @TableName + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
        from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        where   constraint_catalog = DB_NAME() and
                table_name = @TableName
        exec    sp_executesql @sql
    END
GO

Комментариев нет:

Отправить комментарий