如何检查另一个模式中的表是否存在某个索引?

时间:2015-05-29 07:55:20

标签: sql-server

灵感来自此SO Question

我创建了这个程序:

CREATE PROCEDURE [dbo].[dropIndexWithSchema](@schemaName VARCHAR(200), @tableName VARCHAR(200), @indexName VARCHAR(200))
AS
BEGIN
    DECLARE @sql nvarchar(512)

    IF EXISTS (SELECT i.* FROM @schemaName.sys.indexes i WHERE i.name = @indexName AND i.object_id = OBJECT_ID(@schemaName + '.dbo.' + @tableName))
    BEGIN
        SELECT @sql = 'DROP INDEX ' + @indexName + ' ON ' + @schemaName + '.dbo.' + @tableName;
        EXEC sp_executesql @sql
    END
END
GO

当然,这不起作用,因为FROM子句中的@schemaName无法进行参数化。还有一个问题是构造OBJECT_ID函数的对象名称。

我想编写一个过程,它将从模式A中删除模式B中表的索引(如果存在)。

1 个答案:

答案 0 :(得分:0)

尝试

CREATE PROCEDURE [dbo].[dropIndexWithSchema](@schemaName VARCHAR(200), @tableName VARCHAR(200), @indexName VARCHAR(200))
AS
BEGIN
    DECLARE @sql nvarchar(512)
    DECLARE @query NVARCHAR(MAX) = 'SELECT i.* FROM ' + @schemaName+'.sys.indexes i WHERE i.name = '''+@indexName+''' AND i.object_id = OBJECT_ID('''+@schemaName + '.dbo.' + @tableName+''')'
    EXEC sp_executesql @query
    IF (@@rowcount > 0)
    BEGIN
        SELECT @sql = 'DROP INDEX ' + @indexName + ' ON ' + @schemaName + '.dbo.' + @tableName;
        EXEC sp_executesql @sql
    END
END
GO