谢谢大家的cmets。经过一些研究,我能够确定如何使用@mwigdahl 提到的确切表格动态地执行此操作。请看下面的代码:
DECLARE @indexName nvarchar(254),
@tableName nvarchar(254),
@indexType nvarchar(254),
@columnName nvarchar(254),
@isPadded integer,
@ignore_dup_key integer,
@allow_row_locks integer,
@allow_page_locks integer,
@fillFactor integer
SELECT
@indexName = i.name,
@tableName = o.name,
@indexType = i.type_desc,
@columnName = co.[name],
@isPadded = i.is_padded,
@ignore_dup_key = i.[ignore_dup_key],
@allow_row_locks = i.[allow_row_locks],
@allow_page_locks = i.[allow_page_locks],
@fillFactor = i.fill_factor
FROM sys.indexes AS i
INNER JOIN sys.objects AS o ON i.object_id = o.object_id
INNER JOIN sys.index_columns ic on ic.object_id = i.object_id AND ic.index_id = i.index_id
INNER JOIN sys.columns co on co.object_id = i.object_id AND co.column_id = ic.column_id
WHERE
i.[type] = 2 AND
o.[type] = 'U'
DECLARE @sql varchar(max)
SET @sql = 'DROP INDEX [' + @indexName + '] ON [' + @tableName + ']'
EXEC (@sql)
PRINT 'Dropped Index'
-- Do work here
DECLARE @pad_index nvarchar(3),
@ignore_dup nvarchar(3),
@row_locks nvarchar(3),
@page_locks nvarchar(3)
IF @isPadded = 0 SET @pad_index = 'OFF'
ELSE SET @pad_index = 'ON'
IF @ignore_dup_key = 0 SET @ignore_dup = 'OFF'
ELSE SET @ignore_dup = 'ON'
IF @allow_row_locks = 0 SET @row_locks = 'OFF'
ELSE SET @row_locks = 'ON'
IF @allow_page_locks = 0 SET @page_locks = 'OFF'
ELSE SET @page_locks = 'ON'
SET @sql = 'CREATE ' + @indexType + ' INDEX [' + @indexName + '] ON [' + @tableName + ']' +
'(' +
'[' + @columnName + '] ASC' +
') WITH (' +
'PAD_INDEX = ' + @pad_index + ',' +
'STATISTICS_NORECOMPUTE = OFF,' +
'SORT_IN_TEMPDB = OFF,' +
'IGNORE_DUP_KEY = ' + @ignore_dup + ',' +
'DROP_EXISTING = OFF,' +
'ONLINE = OFF,' +
'ALLOW_ROW_LOCKS = ' + @row_locks + ',' +
'ALLOW_PAGE_LOCKS = ' + @page_locks + ',' +
'FILLFACTOR = ' + CONVERT(nvarchar(100),@fillFactor) + ')' +
'ON [PRIMARY]'
PRINT @sql
EXEC (@sql)
PRINT 'Created Index'
我在 SSMS 中使用了Script Index As 函数来查看如何在 T-SQL 中创建索引。
然后我查询了sys.indexes 和sys.index_columns 表以确定哪些属性可用。
代码显示了针对这些表的查询,将这些属性保存到变量中,然后删除并重新创建索引。在我必须硬编码的那些表中,有一些选项不可用。有谁知道这些 OPTIONS 在系统表的某处是否可用?
我希望这对将来的其他人有所帮助。