MS SQL Question Regarding Page/index Defrag.

Apr 17, 2005

I know the shortcut to 'defragging' the database to eliminate and
reclaim 'whitespace' in data and index pages is to setup a maintenance
plan. This doesn't work for me for two reasons:
1. I like to know how things work.
2. I can not create maintenance plans with my hosted provider.
I use the following T-SQL to rebuild all indexes on all tables:

-- exec sp_MSforeachtable "DBCC DBREINDEX ('?', ' ', 90)

But, does that not only address indexes? What about getting whitepace
back from data in tables themselves?
Am I over-thinking this?
When you're paying for SQL by the MB and generate a lot of data (with a
fair amount of churn) you want to keep it optimized and efficient,
right?

View 1 Replies


ADVERTISEMENT

Index Defrag

Dec 5, 2007

I am new to sql server and we have sql server 2000

DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PS_ORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PS0ORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PSAORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PSBORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PSCORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PSEORD_LINE )
DBCC INDEXDEFRAG ( 0, PS_ORD_LINE, PSFORD_LINE )

Please somebody give me for sql server 2005 scripts for above.

View 1 Replies View Related

Does Index Defrag Get Logged?

Sep 15, 2006

I've noticed a huge transaction log size after having run an
index defragmentation. Does a defrag get written to the transaction
log really? (Assuming the full recovery model.)

View 1 Replies View Related

Index Rebuild Does Not Defrag

Oct 3, 2007

Hi,

After issuing an index rebuild on a primary key index (and updating statistics), the index still shows a scan density of 12.5%!

Any ideas on why the rebuild doesn't seem to do anything on the fragmentation levels?

I'm using sql 2005

Thanx

View 12 Replies View Related

Dbreindex Vs Index Defrag Question

Mar 9, 2007

Does anyone know if dbreindex and index defrag ideally perform the same function? I have been told that index defrag does not hold locks on a table when executed and dbreindex does. Other than this is there any difference between the two functions? My understanding was that dbreindex reindexes the data stored in a table for faster reads and index defrag removes purged data. Am I correct? I am currently running both functions on my SQL server and was advised that I really only need to run the index defrag job. Is this advise correct?

View 6 Replies View Related

SQL 2012 :: Clustered Index Defrag Not Working

Apr 15, 2015

I have a clustered index which shows as having a fragmentation level of 66% according to sys.dm_db_index_ physical_ stats.avg_ fragmentation_ in_ percent.

But no matter what I try the fragmentation level doesn't budge. And yes I'm updating the statistics after each attempt.Its not a huge issue the table only has 348 records. I'm testing a fixing fragmentation maintenance script. In Ironing out the syntax of my script I've fixed the fragmentation of indexes of over 65 % anyway..I've come across and index that I can't defragment. I've tried

ALTER INDEX ALL ON [GRIDINFO] REBUILD WITH (FILLFACTOR = 90)

I've tried

ALTER INDEX ALL ON [GRIDINFO] REORGANIZE

I've tried

DBCC INDEXDEFRAG (MYDATABASE, 'GRIDINFO', PK__GRIDINFO__3214EC2721F5FC7F);

The command complete successfully yet the avg_fragmentation_in_percent doesn't change. The table also has a nonclustered index. I've gleaned through all the statements of 'this will have no effect if' but so far I've not spotted a reason why this index won't defrag.The script has been modified to remove schema and database names for the forum.

dbcc showcontig('GRIDINFO','IDX_GRIDINFO1') with tableresults , all_levels
go
DBCC SHOWCONTIG ('GRIDINFO')
go
sp_helpindex 'GRIDINFO'

[code]....

View 3 Replies View Related

DB Engine :: Index Defrag Routine Audit Frag Values

Aug 26, 2015

I am currently re-writing an overnight index defrag procedure and would like to audit indexes in my database - logging the before defrag action" avg fragmentation value and "after defrag action" frag value in an audit table.  This will be for all databases on the server.  I have completed the vast majority of it (cycling though all the databases, detecting which indexes need reorganising or rebuilding and inserting the information into a table) but I cannot get the audit values working properly.  For example, a sample row in my audit table would look like this:

ID Name DB Table frag_before frag_after

1 Index2 DB1 Table6 70.33456 0.03
2 Index7 DB1 Table9 45.98 1.2567etc

View 2 Replies View Related

T-SQL (SS2K8) :: MASTER And MSDB - Defrag Using Standard Alter Index Command?

Oct 10, 2014

On a 2008r2 server, I ran the frag utility against master and msdb and noticed they were severely fragmented.

Is it ok to defrag them using the standard Alter Index command?

View 7 Replies View Related

Transact SQL :: Index Maintenance / Defrag Fails On CDC Enabled Database - 2008 R2

Oct 18, 2012

We have a new database with cdc enabled on all of its tables.  This causes the index maintenance task to fail with following message:

"Executing the query "EXEC DBName.dbo.IndexDefrag_sp" failed with the following error:  "The unique index 'PK_TableName' on source table '[dbo].[TableName]' is used by Change Data Capture.  To alter or drop the index, you must first disable Change Data Capture on the table.  The transaction ended in the trigger. The batch has been aborted.".  Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly" We would like to run the index maintenance without losing the cdc data.  We plan on installing SP2 on SQL Server 2008 R2 soon, would that solve the issue?  Disabling the cdc prior to index maintenance and then re-enabling back upon completion; would delete the data as I found in most discussions, but we would like to retain it. 

View 4 Replies View Related

Sql Index Page Locking

Jan 22, 2008

Hi

I have a table called "Jobs" on my SQL server. I have an access front end which connects to this as well as some access backend tables.
We have 30+ users on the system. There are 1000s of records in this "jobs" table.

For some reason, at certain points of the day all users are stopped from updating a group of records. No-one can update values in a clump of records. It is usually 10-20 records that are numerically together.
When i kick everyone off the system, and log back those particular records seem to be unlocked.

I can rule out permissions on the Jobs table. i am failry certain they have been set correctly.

To me it sounds like Page locking. Now i am new to SQL server. I am inheriting a recently created sql system.

But i notice there are multiple indexes formed on this JOBS table. I looked at one in particular. It is a "ClientName" field.. I noticed under this index > options...it says "Use Page locks when accessing the index".

Am i interpreting this right... But anyone searching under this field, will page lock on that table.
And...if my memory serves me right, "page locking" locks a group of all the nearest records?
Is this correct?

Does this sound like where my system is going wrong?

Thanks

Conor

View 2 Replies View Related

Table/index And Page Mapping

Jul 23, 2005

I've just found a blocking lock occuring in a SQL Server.[color=blue]>From the waitresource, I found that the blocker has the following[/color]information:wait_info: PAGEIOLATCH_EXwait_resource: 14:1:564312And the blockee has the following information:wait_info: LCK_M_Swait_resource: KEY: 14:405576483:2 (7501a5aa8355)The problem is that I do not know which object is the blocker holding,for I understand that for a PAGE lock, it is in the format ofdatabase_id:file_id:page_idI know the db_id, the file_id but don't know how to map the page_id(564312) to a table/index in the database.Can somebody shed some lights on this? thks a lot.

View 4 Replies View Related

Locating A Table Using Index Page

Jul 20, 2005

Hello,I not exactly sure how to determine the table when given the followinginformation:--Could not find the index for RID '999999' in index page('1:99999999'), index id ), database (whatever).--Can you someone tell how I use the system tables to determine whattable this index corresponds to? I'm assuming I used sysindexes andsysobjects somehow.Thanks in advance,JGB_DBA

View 1 Replies View Related

NonClustered Index Page Splitting

Dec 3, 2007


I am attempting to understand the behaviour of a nonclustered index in regards to page splitting.

If I had the following table:-

Col1, Col2, Value

This table has a Clustered index on Col1, Col2 and a NonClustered index on Col2 and include Col1, Values.

If inserts into Col1 were causing page splits in the Clustered index, what are the effects on the NonClustered index?

I am attempting to understand what happens to the NonClustered index in this scenario so that I can make a decision on what fillfactor to use.

View 5 Replies View Related

SQLDataSource - Using The Latest Index From An Insert Elsewhere On A Page

May 22, 2006

I have a page that has a drop down control that is used to control the items in a FormView.  The drop down is bound to one SQLDatasource while the FormView is bound to another SQLDataSource.  I've got everything working great.  Selecting an item in the drop down reveals the details in the form view.  the Form can be opened for editing and deleting.  I even have the Insert working.  But there lies my problem.  Once the Insert is executed I'd like to take the Index value of the recently submitted item and set it to the SelectedIndex of my dropdown.  Here is the code for each of the SQL events  Sub FormViewUpdated(ByVal sender As Object, ByVal e As FormViewUpdatedEventArgs) Handles FormView1.ItemUpdated
confirmation.Visible = True
confirmation.Text = "<img src=""../img/smiley36.gif"">&nbsp;Your record has been updated."

Dim index As Integer = Me.DropDownList1.SelectedIndex
DropDownList1.DataBind()
Me.DropDownList1.SelectedIndex = index
End Sub


Sub FormViewDeleted(ByVal sender As Object, ByVal e As FormViewDeletedEventArgs) Handles FormView1.ItemDeleted
confirmation.Visible = True
confirmation.Text = "<img src=""../img/smiley36.gif"">&nbsp;Your record has been deleted."

DropDownList1.DataBind()
FormView1.ChangeMode(FormViewMode.ReadOnly)
End Sub

Sub FormViewInserted(ByVal sender As Object, ByVal e As FormViewInsertedEventArgs) Handles FormView1.ItemInserted
confirmation.Visible = True
confirmation.Text = "<img src=""../img/smiley36.gif"">&nbsp;Your record has been inserted."
DropDownList1.DataBind()
End Sub
 I would like to do something similar to the Updated event in the Inserted sub.  Notice I have a Me.DropDownList.SelectedIndex bit...I'd like to be able to set a variable to the new ID and then set the Me.DropDownList.SelectedIndex to that variable.  My stored proc for the Insert reads like
  ALTER PROCEDURE dbo.usp_INSERTHelp_Faq
(
@FAQQuestion varchar(500),
@FAQText ntext,
@FAQIndex varchar(500),
@ModifiedBy int,
@Help_FAQID int OUTPUT
)
AS
INSERT INTO Help_FAQ (FAQQuestion, FAQText, FAQIndex,ModifiedBy, Views)
VALUES (@FAQQuestion,@FAQText,@FAQIndex,@ModifiedBy,0)

SELECT @Help_FaqID = @@Identity
RETURN
 So, the Stored Proc is set up to return the latest ID.  Also, my SQLDataSource for the FormView has an InsertParameter:  <asp:Parameter Direction="Output" Name="Help_FAQID" Type="Int32" />
 
Any thoughts on how to close the loop here?  How do I get my hands on the new Help_FAQID?

View 3 Replies View Related

Online Index Rebuild - Same Page Counts After?

Jan 25, 2008

Table A
5.6GB
80 million rows
Initial Page Space Used = 85.7% (sys.dm_db_index_physical_stats - avg_page_space_used_in_percent)

Index and data size are almost unchanged after an ONLINE rebuild of the clustered index. Page count actually goes up by 800. No fill factor or pad index settings. Page space used = 99.2%

During an OFFLINE rebuild the page count drops by ~20%. Page space used = 99.8%.

How can the pages be 99.2% used yet the number of pages hasn't gone done from the ONLINE rebuild?

I'm getting the feeling a shortcut was taken somewhere. Does an ONLINE rebuild only reorganize leaf level index pages but not any of the upper levels? Essentially it puts the pages in order but doesn't do any structure consolidation like OFFLINE?

It would seem that you're missing out on some of the benefits of defragmenting if your data is still spread across more pages and you don't get as many rows per read or it takes more reads to go down your tree to get to your data.

View 8 Replies View Related

Spaced Used By Col In Index Page Is Total Length Of Col Or Data It Stores In It

Apr 9, 2015

i have one col in a nonclusted index which is bigint 8 bytes follwoing result shows min_record_size_in_bytes and max_record_size_in_bytes is 20 that is 12+8 page size is 8 kB. does that mean a record will use 20 bytes in a page or it will only use the space equalent to data stored in the col.what i have seen is page count is same weather i put some data in the col or null

select * From sys.dm_db_index_physical_stats(9,343,null,null,'DETAILED')
database_idobject_idindex_idpartition_numberindex_type_descalloc_unit_type_descindex_depthindex_
levelavg_fragmentation_in_percentfragment_countavg_fragment_size_in_pagespage_countavg_page_
space_used_in_percentrecord_countghost_record_countversion_ghost_record_countmin_
record_size_in_bytesmax_record_size_in_bytesavg_record_size_in_bytesforwarded_
record_countcompressed_page_count
999208304101HEAPIN_ROW_DATA102.9527559055118116253.187540514.196627131208358500016516516500
9992083041141NONCLUSTERED INDEXIN_ROW_DATA202553.21699.3544600938967585000202020NULL0
9992083041141NONCLUSTERED INDEXIN_ROW_DATA2101115.510254509513221600262626NULL0

View 1 Replies View Related

SQL Server 2008 :: Does List Of Page IDs Allocated For A Table Change During Index Rebuilds

Jul 16, 2015

We noticed a deadlock 3-4 weeks ago on a table (table1) and deadlock graph was captured.

When I am analyzing the deadlock graph, page number using DBCC PAGE, I am getting the object id for a different table (table2). But deadlock graph shows the name of the object as table1.

Is it possible that subsequent defragmentation of indexes would have caused the respective page id to got re-allocated to a different table? I checked the deadlock graph lately only after 3-4 weeks.

View 1 Replies View Related

Defrag Or Not To Defrag

Mar 14, 2007

I have been reading many things on the internet and I wanted to create a thread asking my question here. We currently do all the re-indexing and show contig's etc to maintain my sql data and to ensure everything is good to go there.

My question is, what about the physical drive and data. We house our mdf's on a raid 1_0 and our ldfs on raid 5. I am wondering if I need to defrag these drives b/c if not am i impacting my I/O on that box. If so should I stop the sql service so that it does not corrupt SQL data? Any help on this topic would be great.



-patrick

View 1 Replies View Related

Reporting Services :: All Record Are Displaying On One Page - How To Display Page By Page

Nov 11, 2015

I have created one reports but all the records are displaying on one page.find a solution to display the records page by page. I created the same report without group so the records are displaying in page by page.

View 3 Replies View Related

How To Defrag A Table?

Jul 30, 2004

I have a large table with no PK but has other indexes. How to defrag the table (not the indexes)? Do I need to drop and re-create the table or something?

Thanks.

View 3 Replies View Related

Defrag SQL SERVER

Feb 13, 2004

Folks

Our sql server machine is badly in need of a defrag however I'm a bit weary of doing this as I'm really not sure of the implications or indeed how to do it.

I'm really not a server type of person so any assistance would be gratefully received. If anyone can explain it to me like I'm a 5 year old then that would probably be best!



Cheers

View 8 Replies View Related

Database Defrag

Jul 14, 2004

Hello,
I am working with a very large db (850+gig) that is in desperate need of defragging. I am familiar with DBCC Reindex and DBCC IndexDefrag but am concerned that these processes will take an extremely long time to run. Has anyone had any experience with any 3rd party tools that better/faster then DBCC? Or any ideas or suggestions how best to attack this? Among the many tables with large footprints and millions of rows, I have 3 tables with reserved space over 100g also 3 tables with over 500Mil rows (1 tbl with > 1bil rows). This is a 24x7 db.

Thanks in advance for any ideas and suggestions
Jeff

View 2 Replies View Related

Defrag The Drive

Apr 17, 2006

Hi

Can I de-frag the Drive in which the Data files & Log Files of the SQl Server Exists ???

Please Advice.


Thanks

View 5 Replies View Related

Automating Defrag.exe

Jul 19, 2007

Isn't there any way to automate Windows defrag? Isn't there any undocumented parameters for DEFRAG.EXE?

Canada DBA

View 4 Replies View Related

Defrag / Reindex

Oct 21, 2007

I#ve been doing disaster recovery on a web box that died today.

So I thought I'd do some "downtime" maintenance on the DB server

I ran a BDREINDEX on all tables, all indexes. (I know this is the 2000 way, but I assume its as good as the proper 2005 way??).

5 minutes on a 10GB database. Not bad!

I checked the DEFRAG and UPDATE STATS processes that run overnight.

They are basically defragging only tables with SHOWCONTIG indicating fragmentation. And then doing an UPDATE STATISTICS WITH FULLSCAN on all tables

That is taking an average of 30 minutes ...

Is DBREINDEX the equivalent of an UPDATE STATISTICS WITH FULLSCAN, or is it in some way a smaller-sample version?

I'm wondering why I don't just lock the DB and do a REINDEX of everything in 5 minutes ...

Kristen

View 4 Replies View Related

Automating Table Defrag

May 26, 1999

I'd like to build a process that will identify all the tables in a database with a scan density less than 100% and generate 'dbcc dbreindex' statements for them. The 'dbcc showcontig' command displays the information I want but I don't know how to access this information from within a script. Any ideas out there?

View 5 Replies View Related

Defrag Indexed Views?

Jul 7, 2004

How do we defrag indexed views? Can any one give me a query to loop thru all the indexed views in the database and find out the fragmentation levels and also defrag them?
Thanks in advance!

View 1 Replies View Related

How To Defrag SQL Server 2000

Nov 15, 2006

Hi everyone, I am fairly new with SQL Server and need a little bit of help in regards to boosting my SQL servers performance. I have been advised that defraging SQL Server will definitely help solve my issue however I have never performed this function before. Can someone please help guide me through the necessary steps to execute this task. Thanks in advance.

View 5 Replies View Related

Defrag Table With No Clustered Idx

Aug 22, 2007

Is there any easy way to defrag a table with no clustered idx other than bcp out then back in ? (SQL 2000)Actually I have a 100GB db that I deleted data from other tables, about 10GB worth, but access to the table in question (38GB) seems to have slowed down dramatically, Or does the entire disk need to be defragmented and a bcp out/in would be a waste of time on this table ?I run an index defrag every night, reindex weekly.Thanks.

View 14 Replies View Related

YADS -- Yet Another Defrag Script

Oct 2, 2007

This script was based on the original posted here: http://sql-server-performance.com/Community/forums/p/20584/114940.aspx#114940

I use the REORGANIZE option of ALTER INDEX. It's default is ONLINE, no matter what the engine edition and makes for simpler code.

I also make heavy use of my own logging tables, which are included at the bottom of the sp.

Please, feel free to comment. I like getting feedback about my scripts and it seems rarely that happens...


USE Admin
GO

IF EXISTS (SELECT [name] FROM Admin.sys.objects WHERE [name] = 'usp_DB_DeFrag' AND TYPE = 'P')
DROP PROCEDURE dbo.usp_DB_DeFrag
GO

CREATE PROCEDURE dbo.usp_DB_DeFrag (@DBName sysname, @Percentage float = 10)
-- EXEC Admin.dbo.usp_DB_Defrag @DBName = 'FooDB', @Percentage = 10
AS

/******************************************************************************
**Name: Admin.dbo.usp_DB_DeFrag.sql
**
**Description: Defragment indexes using REORGANIZE for online operation.
**Record historical fragmentation information to a permanant table
**for trend/history analysis.
**
**Depends on: SQL2005 >= SP2 due to object_name() usage. See BOL for details.
**Admin.dbo.Process_Log - Table
**Admin.dbo.FragTracking - Table
**
** TODO: Open to suggestions...
**
**Author: G. Rayburn <grayburn@---.com>
**
**Date: 10/02/2007
**
*******************************************************************************
**Modification History
*******************************************************************************
**
**Initial Creation: 10/02/2007 G. Rayburn <grayburn@---.com>
**
*******************************************************************************
**
******************************************************************************/
SET NOCOUNT ON;

DECLARE @DynFragList varchar(1024)
, @DynDBAlter varchar(256)
, @DynDefragDriver varchar(max)
, @DynUpdateStats varchar(1024)
, @OrigRecoveryModel nvarchar(128)
, @Process_Name varchar(150)
, @Message varchar(256)
, @Error int

-- Cursor objects:
, @SchemaName sysname
, @ObjectName sysname
, @IndexName sysname
, @IndexType nvarchar(60)
, @AvgFrag int
, @PageCount int
, @RecordCount int
--, @GhostRecordCnt bigint
--, @Partition int
;


-- DEBUG:
--SET @DBName = 'FooDB'
--SET @Percentage = 10;


SET @Process_Name = 'usp_DB_Defrag run on [' + @DBName + ']';


-- Ensure that @DBName is a valid db for db_id() usage.
IF (db_id(@DBName)) IS NULL
BEGIN
SET @Message = '[' + @DBName + '] is not a valid database on ' + @@SERVERNAME + ', please check your spelling and try again.'

INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'ERROR', 9999, @Message)

RETURN
END;


-- Record startup message:
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'INFO', 0, '[START] - usp_DB_Defrag @DBName = [' + @DBName + '], @Percent = ' + CONVERT(varchar(3),@Percentage) + '.')


-- Check & alter recovery model if neccessary:
SET @OrigRecoveryModel = (SELECT CONVERT(varchar(55),DATABASEPROPERTYEX(@DBName, 'Recovery')))

IF @OrigRecoveryModel = 'FULL'
BEGIN
SET @DynDBAlter = 'ALTER DATABASE [' + @DBName + ']
SET RECOVERY BULK_LOGGED';

EXEC (@DynDBAlter);

SET @Error = (SELECT @@ERROR)
IF @Error = 0
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'SUCCESS', CONVERT(varchar(15),@Error), 'Successfully set database [' + @DBName + '] to BULK_LOGGED recovery model.')
END;
ELSE
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'ERROR', CONVERT(varchar(15),@Error), 'Failed to set database [' + @DBName + '] to BULK_LOGGED recovery model.')
END;
END;
ELSE
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'INFO', 0, 'Database [' + @DBName + '] is in ' + @OrigRecoveryModel + ' recovery model so no need to change it.')
END;



-- Temp table of initial DBCC results:
CREATE TABLE #_FragList
(
ObjectName varchar(100)
, [Object_ID] int
, Index_ID int
, Partition_Number int
, IndexType varchar(60)
, alloc_unit_type_desc nvarchar(60)
, avg_fragmentation_in_percent float
, avg_fragment_size_in_pages float
, avg_page_space_used_in_percent float
, fragment_count bigint
, page_count bigint
, record_count bigint
, forwarded_record_count bigint
, ghost_record_count bigint
);

INSERT INTO #_FragList

SELECT
LEFT(object_name([object_id], db_id(@DBName)),100)
, [object_id]
, index_id
, partition_number
, index_type_desc
, alloc_unit_type_desc
, avg_fragmentation_in_percent
, avg_fragment_size_in_pages
, avg_page_space_used_in_percent
, fragment_count
, page_count
, record_count
, forwarded_record_count
, ghost_record_count

FROM sys.dm_db_index_physical_stats (db_id(@DBName), NULL, NULL, NULL, 'DETAILED')

WHERE avg_fragmentation_in_percent >= @Percentage
AND index_id >= 1
AND page_count >= 1000

ORDER BY -- Ensure Clustered indexes are rebuilt first.
[object_id]
, index_id ASC;

CREATE INDEX IDX_ObjNameIndexID ON #_FragList (ObjectName, Index_id);


-- Historical tracking:
INSERT INTO Admin.dbo.FragTracking

SELECT @DBName
, ObjectName
, [Object_ID]
, Index_ID
, Partition_Number
, IndexType
, alloc_unit_type_desc
, avg_fragmentation_in_percent
, avg_fragment_size_in_pages
, avg_page_space_used_in_percent
, fragment_count
, page_count
, record_count
, forwarded_record_count
, ghost_record_count
, getdate()

FROM #_FragList

ORDER BY [Object_ID]
, Index_ID ASC;


-- Create & populate Temp table to drive defrag operations from.
CREATE TABLE #_DefragDriver
(
IdentID int IDENTITY(1,1)
, SchemaName sysname
, ObjectName sysname
, IndexName sysname
, IndexType varchar(60)
, avg_fragmentation_in_percent float
, page_count int
, record_count int
, ghost_record_count bigint
, partition_number int
);


SET @DynDefragDriver = '
USE [' + @DBName + ']

INSERT INTO #_DefragDriver

SELECT schema_name(so.schema_id)
, fl.[ObjectName]
, si.[name]
, fl.IndexType
, fl.avg_fragmentation_in_percent
, fl.page_count
, fl.record_count
, fl.ghost_record_count
, fl.partition_number

FROM #_FragList fl
, [' + @DBName + '].sys.indexes si
, [' + @DBName + '].sys.objects so

WHERE object_id(fl.ObjectName) = si.object_id
AND fl.index_id = si.index_id
AND object_id(fl.objectname) = so.object_id
AND si.is_disabled = 0
AND si.allow_page_locks = 1

GROUP BY so.schema_id
, fl.[ObjectName]
, fl.[object_id]
, fl.index_id
, si.[name]
, fl.IndexType
, fl.avg_fragmentation_in_percent
, fl.page_count
, fl.record_count
, fl.ghost_record_count
, fl.partition_number

ORDER BY fl.[object_id]
, fl.index_id ASC; '

EXEC (@DynDefragDriver);



-- Do the defrag.
DECLARE curDBFrag CURSOR
FOR

SELECT SchemaName
, ObjectName
, IndexName
, IndexType
, avg_fragmentation_in_percent
, page_count
, record_count
--, ghost_record_count
--, partition_number

FROM #_DefragDriver

ORDER BY IdentID ASC;

OPEN curDBFrag

FETCH NEXT FROM curDBFrag INTO @SchemaName, @ObjectName, @IndexName, @IndexType, @AvgFrag, @PageCount, @RecordCount --, @GhostRecordCnt, @Partition
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN

-- ALTER INDEX operations:
SET @Message = 'Table: [' + @ObjectName + '] with record count: ' + CONVERT(varchar(15),@RecordCount) + ' and page count: ' + CONVERT(varchar(15),@PageCount) + '. Index: [' + @IndexName + '] of type: ' + @IndexType + ' is ' + CONVERT(varchar(5),@AvgFrag) + '% fragmented.';

SET @DynFragList = 'ALTER INDEX [' + @IndexName + '] ON [' + @DBName + '].[' + @SchemaName + '].[' + @ObjectName + '] REORGANIZE;'

EXEC (@DynFragList);

SET @Error = (SELECT @@ERROR)
IF @Error = 0
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'SUCCESS', CONVERT(varchar(15),@Error), @Message)
END;
ELSE
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'ERROR', CONVERT(varchar(15),@Error), @Message)
END;


-- UPDATE STATISTICS operations:
SET @Message = 'UPDATE STATISTICS [' + @SchemaName + '].[' + @ObjectName + '] [' + @Indexname + '];'

SET @DynUpdateStats = '
USE [' + @DBName + ']

UPDATE STATISTICS [' + @SchemaName + '].[' + @ObjectName + '] [' + @Indexname + ']; '

EXEC (@DynUpdateStats);

SET @Error = (SELECT @@ERROR)
IF @Error = 0
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'SUCCESS', CONVERT(varchar(15),@Error), @Message)
END;
ELSE
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'ERROR', CONVERT(varchar(15),@Error), @Message)
END;


-- Friendly WAITFOR operation:
WAITFOR DELAY '00:00:05.000'

END;
FETCH NEXT FROM curDBFrag INTO @SchemaName, @ObjectName, @IndexName, @IndexType, @AvgFrag, @PageCount, @RecordCount --, @GhostRecordCnt, @Partition
END;

CLOSE curDBFrag
DEALLOCATE curDBFrag;


-- Reset FULL recovery model.
IF @OrigRecoveryModel = 'FULL'
BEGIN
SET @DynDBAlter = 'ALTER DATABASE [' + @DBName + ']
SET RECOVERY FULL';

EXEC (@DynDBAlter);

SET @Error = (SELECT @@ERROR)
IF @Error = 0
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'SUCCESS', CONVERT(varchar(15),@Error), 'Successfully reset database [' + @DBName + '] back to FULL recovery model.')
END;
ELSE
BEGIN
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'ERROR', CONVERT(varchar(15),@Error), 'Failed to reset database [' + @DBName + '] back to FULL recovery model.')
END;
END;


-- Record complete message:
INSERT INTO Admin.dbo.Process_Log
VALUES (getdate(), @Process_Name, 'INFO', 0, '[COMPLETE] - usp_DB_Defrag @DBName = [' + @DBName + '], @Percent = ' + CONVERT(varchar(3),@Percentage) + '.');


-- Cleanup:
DROP TABLE #_FragList;
DROP TABLE #_DefragDriver;


-- Dependancies:
----
----USE [Admin]
----GO
---- DROP TABLE Admin.dbo.FragTracking
----CREATE TABLE FragTracking
----( TrackID int IDENTITY(1,1) -- PRIMARY KEY CLUSTERED
----, DBName sysname
----, ObjectName sysname
----, Object_ID int
----, Index_ID int
----, Partition_Number int
----, IndexType varchar(60)
----, alloc_unit_type_desc nvarchar(60)
----, avg_fragmentation_in_percent float
----, avg_fragment_size_in_pages float
----, avg_page_space_used_in_percent float
----, fragment_count bigint
----, page_count bigint
----, record_count bigint
----, forwarded_record_count bigint
----, ghost_record_count bigint
----, SnapDate datetime
----);
----
----USE [Admin]
----GO
---- DROP TABLE Admin.dbo.Process_Log
----CREATE TABLE [dbo].[Process_Log](
----[MessageID] [int] IDENTITY(1,1) NOT NULL,
----[Date] [datetime] NOT NULL,
----[Process_Name] [varchar](150) NULL,
----[Severity] [varchar](15) NULL,
----[ErrorCode] [int] NULL,
----[Message] [varchar](255) NULL,
---- CONSTRAINT [PK_Process_Log] PRIMARY KEY CLUSTERED
----(
----[Date] ASC,
----[MessageID] ASC
----)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Admin_Data]
----) ON [Admin_Data]
----GO
GO

View 18 Replies View Related

DEFRAG Disk Drive

Jul 23, 2005

SQL 2000We took SQL Server offline last night and defragged the SAN. Should wereindex or will be be okay ?Thanks,Craig

View 2 Replies View Related

Difference Between Index Seek &&amp; Index Scan &&amp; Index Lookup Operations?

Oct 20, 2006

please explain the differences btween this logical & phisicall operations that we can see therir graphical icons in execution plan tab in Management Studio

thank you in advance

View 3 Replies View Related

Turn Sql Serveice Off Before Performing Disk Defrag?

Oct 15, 2007

We have a Windows 2003 R2 server running Sql 2005. Should we stop the sql server engine prior to running the "Defrag" utiltiy that comes with the OS? (Maybe we should also disable the NIC card on that machine too....?)

TIA,

barkingdog

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved