欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

重建当前数据库中的所有索引

程序员文章站 2022-04-01 09:48:33
...

重建当前数据库中的所有索引 无 DECLARE @sql nvarchar(500) DECLARE RebuildAllTableIndexes CURSORREAD_ONLYFOR SELECT QUOTENAME(SCHEMA_NAME(tbl.schema_id)) + '.' + QUOTENAME(tbl.NAME) tb_name,QUOTENAME(i.NAME) idx_nameFROM sys.tables AS tblINNE

重建当前数据库中的所有索引
DECLARE @sql nvarchar(500)
 
DECLARE RebuildAllTableIndexes CURSOR
READ_ONLY
FOR 
SELECT QUOTENAME(SCHEMA_NAME(tbl.schema_id)) + '.' + QUOTENAME(tbl.NAME) tb_name,
	QUOTENAME(i.NAME) idx_name
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS i ON (
		i.index_id > 0
		AND i.is_hypothetical = 0
		)
	AND (i.object_id = tbl.object_id)
 
DECLARE @tb_name nvarchar(255), @idx_name nvarchar(255)
OPEN RebuildAllTableIndexes
 
FETCH NEXT FROM RebuildAllTableIndexes INTO @tb_name, @idx_name
WHILE (@@fetch_status  -1)
BEGIN
	IF (@@fetch_status  -2)
	BEGIN
		SET @sql = N'ALTER INDEX ' + @idx_name + N' ON ' + @tb_name + N' REBUILD PARTITION = ALL WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90)'
		EXEC sp_executesql @sql
	END
	FETCH NEXT FROM RebuildAllTableIndexes INTO @tb_name, @idx_name
END
 
CLOSE RebuildAllTableIndexes
DEALLOCATE RebuildAllTableIndexes
GO