Entradas populares

Frase del día


El arte del descanso es una parte del arte de trabajar.

John Ernest Steinbeck (Escritor Estadounidense) 1902 - 19068

CRM 4.0, Worflowlogbase y AsynOperationbase very large



I am really sure, if you are working with Microsoft CRM 4.0 for few time, or you are fighting with it... and you open the database, with a name similar to Your-ORG_MSCRM, and you check this tables:
  • AsyncOperationBase
  • WorkflowLogBase
Look the properties, number of lines and also MB of these tables, sure you will have a fright.... I am sure they have a lot of lines, and also an important size in MB, I bet they do... The reasons for this:

  1. The CRM 4.0 by default doesn´t delete the finished workflows, due to this in the Workflowlogbase table, a lot of unnecessary information is stored.

  2. The Asyncoperationbase table, is used to save information of Microsoft CRM Asynchronous Processing Service (MSCRMAsyncService), which lead again in a lot of unnecessary information is stored.
The steps we will follow to solve the problem are the following:
  1. The first step is ESSENTIAL, make a complete backup of CRM DATABASES

  2. We will modify or add some keys in the register, to avoid finished Workflows to be stored in the database

  3. We will run some scripts in the database that will empty Worflowlogbase and Asyncoperationbase tables
Well, lets work...

1-Backup

Well..., I think all of you Know how to make a SQLSERVER backup.... so I will jump this step... If you don´t know how to make a backup... I am not sure if you should continue readinf this article.... (well anyway if you google you will find how to make a backup easyly)

2-Windows Register Modification:
  • Go to this branch of the register Windows HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM

  • Check if the following key exists AsyncRemoveCompletedWorkflows, in case that exist change the value of this key to 1

  • In the case that this value doesn´t exist, we will create a DWORD key with the next name AsyncRemoveCompletedWorkflows and set the value of this register in 1

  • We wil execute an IISRESET in a MSDOS window, this will restart IIS services.
¿What are we doing setting the value of this register in 1 or adding the key AsyncRemoveCompletedWorkflows in the Windows register? By Default CRM 4.0 save in the databse all workflows, even those which had finished, for the majority of us this information is unusable, setting this register AsyncRemoveCompletedWorkflows to 1 no more finished workflows will be stored in the CRM database.

3-Running scripts to empty the lines of the Workflowlogbase and Asyncoperationbase.

Now in the CRM 4.0, no more finished workflows will be stored. But... how we should proceed to delete the information of those finished workflows that has been saved previously in Workflowlobase and Asyncoperationbase tables? , sure that there are hundreds, thousands, or probably millions of lines... don´t worry we have a solution for this... Remember that these scripts must be executed in the database which name is similar to this Your-ORG_MSCRM

  • Stop "Microsoft CRM Asynchronous Processing Service"
  • Second step we will create indexes to optimize the script execution:
CREATE NONCLUSTERED INDEX CRM_WorkflowLog_AsyncOperationID ON [dbo].[WorkflowLogBase] ([AsyncOperationID])
GO

CREATE NONCLUSTERED INDEX CRM_DuplicateRecord_AsyncOperationID ON [dbo].[DuplicateRecordBase] ([AsyncOperationID])
GO

CREATE NONCLUSTERED INDEX CRM_BulkDeleteOperation_AsyncOperationID ON [dbo].[BulkDeleteOperationBase] (AsyncOperationID)
GO

  • Third step, update and rebuild the following indexes:
ALTER INDEX ALL ON AsyncOperationBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO

ALTER INDEX ALL ON WorkflowLogBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO
  • Fourth step, update all statystics involved in the queries...
UPDATE STATISTICS [dbo].[AsyncOperationBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[DuplicateRecordBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[BulkDeleteOperationBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowCompletedScopeBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowLogBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowWaitSubscriptionBase] WITH FULLSCAN

  • Last step, this is the script that will delete the unusable information from this two tables:

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


Una vez hecho esto ir a mirar el tamaño de estas dos tablas y veréis el resultado.....
Comentaros:

  • It is essential, follow the previous steps, before running the delete script. The create indixes, update statystics etc... if not, it will take a hundred years before finish the delete of the line... (I am talking for my own exprience, had to stop the script after more than some hours running)

  • Do Not execute the scripts during peak hours.

That´s it.... hurry up executing scripts, and deleting unuseful information from your CRM database

Source:

CRM 4.0, tablas Worflowlogbase y AsynOperationbase muy grandes



Seguro que los que trabajáis con el CRM 4.0 de Microsoft, hace poco que os estáis peleando con el y abrís la base de datos vais a la base de datos que se llama _MSCRM, y vais a revisar estas dos tablas:
  • AsyncOperationBase
  • WorkflowLogBase

En las propiedades de las tablas mirad, en tamaño y número de filas de estas tablas, seguro que os lleváis una sorpresa.... ¿A que tienen un montón de registros y ocupan muchos MB? Los motivos que provocan esto:

  1. El CRM 4.0 por defecto no elimina los flujos de trabajo (workflows) que han finalizado por lo que en la tabla workflowlogbase, se almacena mucha información innecesaria

  2. La tabla Asyncoperationbase, se emplea para guardar información del servicio asincrónico del CRM (prometo que así lo llama microsoft) MSCRMAsyncService, lo que vuelve a provocar que se guarde mucha información innecesaria.

Los pasos que seguiremos serán los siguientes:
  1. El primer paso e IMPRESCINDIBLE, HACED UNA COPIA COMPLETA DE LAS BASES DE DATOS DEL CRM

  2. Modificaremos unas claves del registro, para evitar que los workflows finalizados se guarden en la base de datos

  3. Ejecutaremos unos unos scripts en la base de datos que vaciarán las tablas Worflowlogbase y Asyncoperationbase.

Bueno pues al lio...

1-Copia de seguridad

Esto..., me imagino que ya sois mayorcitos, y además si estáis leyendo este articulo voy a presuponer que ya sabeis como hacerla..., asi que me saltaré este paso...

2-Modificación del registro de Windows:
  • iremos a la siguiente rama del registro de Windows HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM

  • Revisaremos si existe la siguiente clave AsyncRemoveCompletedWorkflows en el caso de que exista pondremos el valor de esta clave a 1

  • En el caso de que no exista crearemos un registro de tipo DWORD con el nombre AsyncRemoveCompletedWorkflows con el valor de este registro a 1

  • Ejecutaremos desde la linea de comandos un iisreset, que reinicirá los servicios del IIS
¿Que hacemos al añadir o poner a uno la clave del registro AsyncRemoveCompletedWorkflows? Por defecto el CRM 4.0 guarda en la BBDD los flujos de trabajo o Workflows, que han finalizado, para la mayoría de nosotros esta información que se guarda en la base de datos no es necesaria, al poner este registro AsyncRemoveCompletedWorkflows con valor 1, a partir de ese momento los workflows finalizados no se guardarán en la BBDD

3-Ejecución de scripts para vaciar de información las tablas Worflowlogbase y Asyncoperationbase.

Ahora el CRM 4.0 ya no guardará más workflows que hayan finalizado, pero que hacemos con los registros de las tablas Workflowlobase y Asyncoperationbase, que seguro que son cientos, miles o con toda seguridad varios millones... bien no preocuparos... Comentaros que todos estos scripts los debeis ejecutar en la base de datos cuyo nombre será algo similar a esto _MSCRM

  • Debeis para el "servicio de Procesamiento asincrónico de Microsoft CRM"

  • Paso Segundo vamos a crear unos indices para optimizar la ejecución del script:
CREATE NONCLUSTERED INDEX CRM_WorkflowLog_AsyncOperationID ON [dbo].[WorkflowLogBase] ([AsyncOperationID])
GO

CREATE NONCLUSTERED INDEX CRM_DuplicateRecord_AsyncOperationID ON [dbo].[DuplicateRecordBase] ([AsyncOperationID])
GO

CREATE NONCLUSTERED INDEX CRM_BulkDeleteOperation_AsyncOperationID ON [dbo].[BulkDeleteOperationBase] (AsyncOperationID)
GO

  • Paso tercero, reconstruir y actualizar los siguiente indices:
ALTER INDEX ALL ON AsyncOperationBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO

ALTER INDEX ALL ON WorkflowLogBase REBUILD WITH (FILLFACTOR = 80, ONLINE = OFF,SORT_IN_TEMPDB = ON, STATISTICS_NORECOMPUTE = OFF)
GO
  • Paso cuarto actualizar todas las estadísticas que se verán involucradas en las queries...
UPDATE STATISTICS [dbo].[AsyncOperationBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[DuplicateRecordBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[BulkDeleteOperationBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowCompletedScopeBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowLogBase] WITH FULLSCAN
UPDATE STATISTICS [dbo].[WorkflowWaitSubscriptionBase] WITH FULLSCAN

  • Paso quinto y último es la ejecución del script que realmente borrar la información superflua de estas dos tablas:

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


Una vez hecho esto ir a mirar el tamaño de estas dos tablas y veréis el resultado.....
Comentaros:

  • Que es imprescindible realizar los pasos previos de creación de indices, actualizar estadísticas etc... porque sino, va a tardar un mas de un siglo en acabar... (por experiencia propia lo digo, tuve que parar el script a la mitad de ejecución

  • No ejecutar estos scripts durante horas puntas de trabajo


Bueno pues ya está, ale ale, a ejecutar scripts y borrar información innecesaria de la base de datos....

Fuente:

Frase del día


¿Por qué esta magnífica tecnología científica, que ahorra trabajo y nos hace la vida mas fácil, nos aporta tan poca felicidad? La repuesta es está, simplemente: porque aún no hemos aprendido a usarla con tino.

Albert Einstein Científico alemán nacionalizado estadounidense

How to export data from a Database to Excel?

In this entry I will explain how to export data from a Database (in this case Oracle) using Excel (version 2007). The point is that later We can import this information easily in other database, and Excel files allow us to modify it very simply

Well lets get to work, the procedure is very easy,,,,

1-First of all we should configure a ODBC connection against the Database, in our cas ORACLE, to do this we should go, to Administrative tools -> Data Sources (ODBC)


2-In the ODBC, we will check that we have installed the driver we will use to connect to the Database, in this case we will use driver named Oracle in ora92 (we have installed previously)


3- Then we will open Excel (the Excel version we use is 2007), and we will set and we will configure and External Origin of Data. To do this, go to the tab Data -> From Other Sources -> From Microsoft Query, as we can see in the screenshot.


4- In the next screen we will select New Data Origin (the part marked with the red box)


5-Now we have to type the name of the connection we are setting up (the one you want), and the driver of the connection we will use, as we said before Oracle in Ora92



6-And Now click on the connect button, and a new windows will appear, and we will be asked to type, SERVICE of the Oracle database, a USER and PASSWORD. Remenber that this user may have permissions to do selects to the database from which we want to export data


7- Now a new window will appear, in it we will be able to see the tables of our database, we will select the table from which we want to export the data


8- If we click in the table we will see the columns of it


9 - And it we click on the arrow in the red box, we will add all the columns to the select.


10- In the next screen, we will select the option View data or Edit Query in Microsoft query


11- Once we have done this, Microsoft Query will be opened, in which we will able to see the data of the table, and all the columns of it.... and if now we click on the button in the red box , where we can read SQL



12- Now, is the most interesting part, a window will be open, and we will see the select that is being executed, and modify it for our liking. In the screenshot yo will see that this is a good old SELECT. IMPORTANT REMEMBER THAT AS WE ARE WORKING AGAINST A ORACLE DATABASE THE T-SQL, MUST BE ORACLE T-SQL

13- Once we have modified the select to our needs, and we need to be returned the data to Excel, just click File -> Return data to Microsoft Excel


14- Excel will be opened with the next windows, we will click accept.



15- When we have finished all these steps, Excel will be opened, and it will show all the data from the select we have done.


And Folks, have the information in Excel can give use a lot of possibilities to work with this data, whether it is, import this file directly to other database , conver this file into an other kind of file.... in sum everything we want...

Have fun exporting you data.... :-D

¿Como exportar datos de una base de datos con Excel?

En esta entrada os voy a explicar como exportar datos de una base de datos (en este caso de ORACLE) empleando Excel (la versión 2007). La gracia de esto es que después podemos importarla facilmente a otra base de datos diferente, y un fichero de Excel nos permite modificar el contenido del fichero con mucha facilidad....

Bueno vamos al lío, el procedimiento es muy sencillo

1- Deberemos configurar una conexión ODBC contra la base de datos, en nuestro caso ORACLE,para eso en Windows iremos a Herramientas Administrativas -> Orígenes de Datos (ODBC)


2- Dentro de ODBC, revisaremos que tenemos instalado el driver que vamos a utilizar para conectarnos a la Base de Datos, en este ejemplo utilizaremos el driver que se llama Oracle in ora92 que hemos instalado previamente.

3- Seguidamente abriremos el Excel (la versión de Excel que empleo en este caso es la 2007), y le diremos que queremos emplear un origen de datos externo. Para eso iremos a la pestaña de Datos -> Otras fuentes -> Desde Microsoft Query como vemos en la captura de pantalla.

4- Ahora aparecerá la siguiente ventana en la seleccionaremos nuevo origen de datos (el recuadro en rojo.

5- Ahora deberemos introducir el nombre de la conexion que estamos creando (el que vosotros queráis), y el driver de conexión que vamos a emplear, como ya hemos dicho antes emplearemos Oracle in ORA92


6- Ahora daremos al botón de conectar, y nos aparecerá una nueva ventana en la que se nos pedirá introduzcamos el, Service Name de la base de datos de Oracle, un USUARIO y PASSWORD. Recordad que este usuario tiene que tener permisos para poder hacer consultas a la base de datos de la cual queremos exportar datos.


7 - Y ahora nos aparecerá una nueva pantalla en la que ya podremos ver las tablas de nuestra base de datos, seleccionaremos una tabla cualquiera...


8- Si clicamos en la tabla podremos ver las columnas de la misma


9 - Y si clicamos en la flecha señalada con el recuadro rojo de esta ventana añadiremos todas las columnas a la consulta.




10 - En la siguiente pantalla, seleccionaremos la opcion Ver Datos o Modificar en Microsoft Query


11- Una vez hecho esto se nos abrira, el Microsoft Query, en el que podremos ver los datos de la tabla, y los campos de la misma...y si ahora clicamos en el boton con el recuadro rojo en el que pone SQL


12- Ahora es cuando viene lo bueno, se nos abrirá una ventana en la que podemos ver la select que se esta ejecutando y modificarla a nuestro gusto. En a captura de pantalla ya veis que esto es una SELECT de las toda la vida... IMPORTANTE: RECORDAD QUE COMO ESTAMOS ATACANDO A UNA BBDD ORACLE EL T-SQL DEBE SER EL DE ORACLE.

13- Una vez hayamos modificado la consulta a nuestro gusto y quisieramos que nos devolviera los datos a Excel, simplemente iríamos a Archivo -> Devolver datos a Microsoft Excel


14- Se nos abrirá el Excel con la siguiente ventana, a la que daremos a aceptar.


15- Una vez realizados todos estos pasos se nos abrira el excel y nos devolverá los datos de la consulta que hayamos modificado


Y amigos el tener los datos en Excel nos da infinidad de posibilidades a la hora de tratar los datos, ya sea para importar este fichero directamente a otra base de datos, transformarlo en otro tipo de fichero... en fin todo lo que se nos pueda ocurrir....

Que lo paséis bien exportando datos....