Delete log and rebuild index of AsyncOperationBase and WorkflowLogBase table in Dynamics CRM using SQL Job


USE [msdb]
GO
/****** Object:  Job [Async-CleanUP]    Script Date: 05/27/2010 12:36:09 ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]]    Script Date: 05/27/2010 12:36:09 ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]’ AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N’JOB’, @type=N’LOCAL’, @name=N'[Uncategorized (Local)]’
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N’Async-CleanUP’,
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=0,
@description=N’No description available.’,
@category_name=N'[Uncategorized (Local)]’,
@owner_login_name=N’domain\username’, @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Async-CleanUp-TSQL]    Script Date: 05/27/2010 12:36:09 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N’Async-CleanUp-TSQL’,
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N’TSQL’,
@command=N’IF EXISTS (SELECT name from sys.indexes
WHERE name = N”CRM_AsyncOperation_CleanupCompleted”)
DROP Index AsyncOperationBase.CRM_AsyncOperation_CleanupCompleted
GO
CREATE NONCLUSTERED INDEX CRM_AsyncOperation_CleanupCompleted
ON [dbo].[AsyncOperationBase] ([StatusCode],[StateCode],[OperationType])
GO
declare @DeleteRowCount int
Select @DeleteRowCount = 2000
declare @DeletedAsyncRowsTable table (AsyncOperationId uniqueidentifier not null primary key)
declare @continue int, @rowCount int
select @continue = 1
while (@continue = 1)
begin
begin tran
insert into @DeletedAsyncRowsTable(AsyncOperationId)
Select top (@DeleteRowCount) AsyncOperationId
from AsyncOperationBase
where OperationType in (1, 9, 12, 25, 27, 10) AND StateCode = 3 AND StatusCode in (30, 32)

Select @rowCount = 0
Select @rowCount = count(*) from @DeletedAsyncRowsTable
select @continue = case when @rowCount <= 0 then 0 else 1 end

if (@continue = 1)
begin
delete WorkflowLogBase from WorkflowLogBase W, @DeletedAsyncRowsTable d
where W.AsyncOperationId = d.AsyncOperationId

delete BulkDeleteFailureBase From BulkDeleteFailureBase B, @DeletedAsyncRowsTable d
where B.AsyncOperationId = d.AsyncOperationId

delete AsyncOperationBase From AsyncOperationBase A, @DeletedAsyncRowsTable d
where A.AsyncOperationId = d.AsyncOperationId

delete @DeletedAsyncRowsTable
end

commit
end
–Drop the Index on AsyncOperationBase
DROP INDEX AsyncOperationBase.CRM_AsyncOperation_CleanupCompleted

–rebuild index
— Rebuild Indexes & Update Statistics on AsyncOperationBase Table
ALTER INDEX ALL ON AsyncOperationBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO
— Rebuild Indexes & Update Statistics on WorkflowLogBase Table
ALTER INDEX ALL ON WorkflowLogBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO
‘,
@database_name=N'<Organization Name>_MSCRM’,
@flags=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N’Async-Cleanup-Schedule’,
@enabled=1,
@freq_type=8,
@freq_interval=18,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20091116,
@active_end_date=99991231,
@active_start_time=0,
@active_end_time=235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)’
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

Rebuild Index of a database table


DECLARE @Database VARCHAR(255)
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)

DECLARE @fillfactor INT
SET @fillfactor = 90

CREATE Table #databaseName (dbid int identity(1,1), DbName Varchar(255))

Insert into #databaseName
SELECT name
FROM   MASTER.dbo.sysdatabases
—  WHERE  name NOT IN ( ‘master’, ‘model’, ‘msdb’, ‘tempdb’, ‘distrbution’ )
WHERE  name IN ( ‘OD’)
ORDER  BY 1

CREATE Table #TableName (Tableid int identity(1,1), TableName Varchar(1000))

declare @DbCnt int
declare @TblCnt int
declare @i int
declare @j int

select @i = 1
select @j = 1

select @DbCnt = Max(dbid) from #databaseName

WHILE @i <= @Dbcnt
BEGIN
SELECT @cmd = ‘Insert Into #TableName SELECT table_catalog + ”.” + table_schema + ”.” + table_name as tableName
FROM ‘ + DbName + ‘.INFORMATION_SCHEMA.TABLES WHERE table_type = ”BASE TABLE”’
from #databaseName where dbid = @i

— create table cursor
Print @cmd
EXEC (@cmd)

select @tblCnt = Max(Tableid) from #tableName

WHILE @j <= @tblcnt
BEGIN
— SQL 2000 command
–DBCC DBREINDEX(@Table,’ ‘,@fillfactor)
— SQL 2005 command
SELECT @cmd = ‘ALTER INDEX ALL ON ‘ + TableName + ‘ REBUILD WITH (FILLFACTOR = ‘ + Convert(VARCHAR(3), @fillfactor) + ‘)’
From #tableName where Tableid = @j

print @cmd
EXEC (@cmd)

Set @j =@j + 1
END

Set @i =@i + 1

END

drop table #databaseName
drop table #tableName

%d bloggers like this: