오랜 기간 동안 데이터베이스를 정리하지 않았다면 insert, update, delete 등의 명령 실행으로 인해 데이터와 인덱스 페이지가 상당 부분 조각 조각나 있을 것이다. 이 SQL 스크립트는 데이터베이스 조각 정리를 도와준다.
SQL 스크립트 소스는 다음과 같다.
--Re-indexes the specified database
CREATE PROCEDURE usp_DefragDatabase
-- We don't use sysname because it might not be long enough.
-- sysname is 128 chars, so we use double that.
@dbname nvarchar(256)
AS
BEGIN
-- Quote the database name with brackets
DECLARE @quoteddbname nvarchar(256)
set @quoteddbname = quotename( @dbname )
-- The outer EXEC is so we can do USE, not allowed in stored procs
-- The inner EXEC does the actual reindex on each table in the
-- specified database
EXEC('
USE '+ @quoteddbname +'
DECLARE @sTableName sysname
DECLARE PKMS_Tables CURSOR LOCAL FOR
select table_name from information_schema.tables
where table_type = ''base table'' order by 1
OPEN PKMS_Tables
FETCH NEXT FROM PKMS_Tables INTO @sTableName
WHILE @@FETCH_STATUS = 0
BEGIN
select @sTablename = quotename(@sTablename, ''[]'')
EXEC('' DBCC DBREINDEX ( ''+@sTableName+'') WITH NO_INFOMSGS'')
FETCH NEXT FROM PKMS_Tables INTO @sTableName
END
CLOSE PKMS_Tables')
END
GO
|