2

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

我在检查是空还是空时遇到了一些麻烦,还要检查表是否存在是否有比嵌套 if 更优雅的方法来检查表是否存在并且参数不为空或空?

这适用于 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
4

1 回答 1

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
于 2012-08-29T15:05:39.410 回答