灵感来自此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中表的索引(如果存在)。
答案 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