清理约束的存储过程

时间:2012-08-29 14:58:10

标签: sql-server sql-server-2008-r2

我正在尝试创建一个存储过程来清除表中的约束。

我有一些麻烦,检查是null还是空,还要检查是否存在表是否存在比nest更优雅的方法如果检查表是否存在且参数不是null还是空?

这适用于SQL Server 2008 R2。

ALTER PROCEDURE [dbo].[sp_quitarConstrain](@table NVARCHAR(50))
AS
DECLARE @database NVARCHAR(50)
DECLARE @sql NVARCHAR(255)
SET @database = 'table'

IF((COALESCE(@table,'') <> '') OR (@table IS NULL))
    BEGIN
        PRINT 'Necesitas dar una tabla valida'
        RETURN 
    END
ELSE
    BEGIN
        WHILE EXISTS(SELECT * FROM sys.foreign_keys WHERE referenced_object_id = object_id(+ @table))
        BEGIN
            SELECT    @sql = 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + name 
            FROM    sys.foreign_keys 
            WHERE    referenced_object_id = object_id(@table)

            EXEC    sp_executesql @sql
        END
    END

1 个答案:

答案 0 :(得分:2)

您的存储过程确实有效,只需稍作更改 - 例如(COALESCE(@table,'') <> '')应为(COALESCE(@table,'') = '')

ALTER PROCEDURE [dbo].[sp_quitarConstrain](@table NVARCHAR(50))
AS
    DECLARE @sql NVARCHAR(255)

    IF((COALESCE(@table,'') = '') OR (@table IS NULL))
        BEGIN
            PRINT 'Necesitas dar una tabla valida'
            RETURN 
        END
    ELSE
        BEGIN
            WHILE EXISTS(SELECT * FROM sys.foreign_keys WHERE referenced_object_id = object_id(@table))
                BEGIN
                    SELECT    @sql = 'ALTER TABLE ' + OBJECT_NAME(parent_object_id) + ' DROP CONSTRAINT ' + name 
                    FROM    sys.foreign_keys 
                    WHERE    referenced_object_id = object_id(@table)
                    EXEC    sp_executesql @sql
                END
        END

如果您对模式不太挑剔,可以检查表格如下:

IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE name=@table)
    BEGIN
        PRINT 'Necesitas dar una tabla valida'
        RETURN 
    END