3

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

无论如何,简而言之,我想测试某个列是否有索引,如果有,则删除该索引。我想知道是否可以通过将索引名称传递给 DROP INDEX 语句来做到这一点。

首先,仅供参考,表名是“帐户”,列名是“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 语句,而不是对索引名称进行硬编码。我想这可以通过声明一个变量并以某种方式将其设置为查询结果来完成,但我不知道该怎么做。可以做到吗?

4

2 回答 2

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到上面的查询中,因为它可能返回多个索引。

于 2013-09-25T04:02:04.110 回答
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
于 2013-09-25T05:29:59.460 回答