SqlServer教程

SQLServer重建索引

本文主要是介绍SQLServer重建索引,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
 

查询碎片率

SELECT a.index_id ,B.name [IndexName] ,avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats ( DB_ID() , NULL , NULL, NULL, NULL ) AS A
JOIN sys.indexes AS B ON a.object_id = b.object_id AND a.index_id = b.index_id
inner JOIN sys.tables AS C ON a.object_id=C.object_id
inner JOIN sys.schemas AS D ON C.schema_id=D.schema_id
WHERE a.index_id > 0
order by avg_fragmentation_in_percent desc
USE db;
GO
DBCC SHOWCONTIG WITH TABLERESULTS, ALL_INDEXES;
GO

查询

SELECT creation_time N'语句编译时间'
,last_execution_time N'上次执行时间'
,total_physical_reads N'物理读取总次数'
,total_logical_reads/execution_count N'每次逻辑读次数'
,total_logical_reads N'逻辑读取总次数'
,total_logical_writes N'逻辑写入总次数'
, execution_count N'执行次数'
, total_worker_time/1000 N'所用的CPU总时间ms'
, total_elapsed_time/1000 N'总花费时间ms'
, (total_elapsed_time / execution_count)/1000 N'平均时间ms'
,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
- qs.statement_start_offset)/2) + 1) N'执行语句'
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
where SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
((CASE statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END
- qs.statement_start_offset)/2) + 1) not like'%fetch%'
ORDER BY total_elapsed_time / execution_count DESC;

单表重建

use[数据库名]
ALTER INDEX ALL ON [表名称] REBUILD;

 

索引重建

Use [数据库名称]
Go
DECLARE @DBCCString NVARCHAR(1000)
DECLARE @TableName VARCHAR(100)
DECLARE Cur_Index CURSOR
FOR
SELECT Name AS TblName
FROM sysobjects
WHERE xType='U'
ORDER BY TblName
FOR READ ONLY
OPEN Cur_Index
FETCH NEXT FROM Cur_Index
INTO @TableName
WHILE @@FETCH_STATUS=0
BEGIN
SET @DBCCString = 'DBCC DBREINDEX(@TblName,'''')WITH NO_INFOMSGS'
EXEC SP_EXECUTESQL @DBCCString,N'@TblName VARCHAR(100)', @TableName
PRINT '重建表' + @TableName +'的索引........OK!'
FETCH NEXT FROM Cur_Index INTO @TableName
END
CLOSE Cur_Index
DEALLOCATE Cur_Index
PRINT '操作完成!'
go


DBCC UPDATEUSAGE(0);

 

这篇关于SQLServer重建索引的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!