Microsoft Dynamics 365 Blog

In AX 2009 it may happen that you delete a company but data related to this company remain in the database.
You can use a SQL script similar to the following to delete this data

NOTE: Use with caution! We recommend you take appropriate actions to backup the database first before attempting to delete any data:

/*This programming example is for illustration purposes only. Microsoft disclaims all warranties and conditions with regard to use of the programming example for other purposes. Microsoft shall not, at any time, be liable for any special, direct, indirect or consequential damages, whether in an action of contract, negligence or other action arising out of or in connection with the use or performance of the programming example. Nothing herein should be construed as constituting any kind of warranty.*/

DECLARE @_tableName nvarchar(40)
DECLARE @_companyId nvarchar(4)

SET @_companyId = N'<company_id>’;  — replace  with required company

DECLARE curSqlDictionary CURSOR FOR
SELECT A.SQLNAME
FROM SQLDICTIONARY A
INNER JOIN SQLDICTIONARY X ON X.TABLEID = A.TABLEID AND X.FIELDID = 61448
WHERE A.FIELDID = 0
 AND A.FLAGS = 0

OPEN curSqlDictionary

FETCH NEXT FROM curSqlDictionary INTO @_tableName

WHILE @@FETCH_STATUS = 0
BEGIN
 DECLARE @_sql nvarchar(4000)
 SET @_sql = N’DELETE FROM ‘ + QUOTENAME(@_tableName) + N’ WHERE DATAAREAID = @_dataAreaId’
 
 EXEC sp_executesql @_sql, N’@_dataAreaId nvarchar(4)’, @_dataAreaId = @_companyId 
 
 FETCH NEXT FROM curSqlDictionary INTO @_tableName
END

CLOSE curSqlDictionary
DEALLOCATE curSqlDictionary

 

–author: Martin Falta
–editor: Daniel Durrer
–date: 09/Dec/2010

We're always looking for feedback and would like to hear from you. Please head to the Dynamics 365 Community to start a discussion, ask questions, and tell us what you think!