将变量传递给DROP INDEX语句

时间:2013-09-25 03:50:08

标签: sql-server tsql

我刚刚注册并希望这是有道理的。

无论如何,简而言之,我想测试某个列是否有索引,如果是,请删除索引。我想通过索引名称传递给DROP INDEX语句来查明是否可以这样做。

首先,FYI表格名称为“帐户”,列名称为“ID”。

为了测试索引是否存在,我使用以下内容(不要认为我是一个天才,我从这里得到了SELECT语句): http://social.msdn.microsoft.com/Forums/sqlserver/en-US/e183be6c-1177-4f81-b130-aeeeff7638fe/how-do-you-check-if-an-index-exists-for-sql-table-column

IF EXISTS 
(SELECT 
    sysindex.name AS IndexName
FROM 
    sys.indexes AS SysIndex
    INNER JOIN sys.index_columns AS SysIndexCol ON SysIndex.object_id = SysIndexCol.object_id AND SysIndex.index_id = SysIndexCol.index_id 
    INNER JOIN sys.columns AS SysCols ON SysIndexCol.column_id = SysCols.column_id AND SysIndexCol.object_id = SysCols.object_id 
WHERE 
   type <> 0 
   AND SysIndex.object_id in (Select systbl.object_id from sys.tables as systbl
   WHERE SysTbl.name = 'Account')
   AND SysCols.name = 'ID')

DROP INDEX dbo.Account.Account$ID;
GO

在上面的DROP INDEX语句中,我对索引名称('Account $ ID')进行了硬编码 - 如果您自己运行SELECT语句,它会显示名称,但无论如何它也很容易通过SSMS识别。 但是,而不是硬编码索引名称,我希望能够以某种方式将索引名称(正如我所说,由SELECT语句显示)传递给DROP INDEX语句。我想这将通过声明一个变量并以某种方式将其设置为查询结果来完成,但我不知道该怎么做。可以吗?

2 个答案:

答案 0 :(得分:2)

你可以使用类似的东西。请注意,表名已设置为变量。

DECLARE @index_name NVARCHAR(MAX), @table_name NVARCHAR(MAX)

SET @table_name = 'Account'  -- your table name

SELECT TOP 1
    @index_name = sysindex.name
FROM 
    sys.indexes AS SysIndex
    INNER JOIN sys.index_columns AS SysIndexCol ON SysIndex.object_id = SysIndexCol.object_id AND SysIndex.index_id = SysIndexCol.index_id 
    INNER JOIN sys.columns AS SysCols ON SysIndexCol.column_id = SysCols.column_id AND SysIndexCol.object_id = SysCols.object_id 
WHERE 
   type <> 0 
   AND SysIndex.object_id in (Select systbl.object_id from sys.tables as systbl
   WHERE SysTbl.name = @table_name)
   AND SysCols.name = 'id'

DECLARE @sql NVARCHAR(MAX) = N'DROP INDEX dbo.' + @table_name + '.' + @index_name

IF @index_name IS NOT NULL
    exec sp_executesql @sql

修改

我在上面的查询中添加了TOP 1,因为它可能会返回多个索引。

答案 1 :(得分:1)

试试这个 -

DECLARE @index_name SYSNAME
    ,   @table_name SYSNAME = 'dbo.Account'
    ,   @column_name SYSNAME = 'ID'

SELECT @index_name = i.name
FROM sys.indexes i
JOIN sys.index_columns ic ON i.[object_id] = ic.[object_id] 
    AND i.index_id = ic.index_id
WHERE i.[type] > 0
    AND i.[object_id] = OBJECT_ID(@table_name)
    AND COL_NAME(i.[object_id], ic.column_id) = @column_name

DECLARE @SQL NVARCHAR(MAX) = 'DROP INDEX ' + @table_name + '.' + @index_name
EXEC sp_executesql @SQL