Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Tuesday, November 21, 2017

Delete Excess Data in Table TaxDocumentJson from SQL command in Microsoft Dynamics AX

Delete Excess Data in Table TaxDocumentJson from SQL command in Microsoft Dynamics AX


Remove the excess data in TaxDocumentJson at in AX HQ. Please carry this out on a UAT environment. Once this is tested successfully, you can do the same steps on Production.
Run the following SQL query to remove excess data
DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;
WHILE (@Deleted_Rows > 0)
  BEGIN
   BEGIN TRANSACTION
   -- Delete some small number of rows at a time
     DELETE TOP (10) j from taxdocumentjson j
inner join TaxDocumentRow r on r.TAXDOCUMENTJSON = j.ID;
SET @Deleted_Rows = @@ROWCOUNT;   
   COMMIT TRANSACTION
   CHECKPOINT -- for simple recovery model
END
You can count the number of the records required to be cleaned via another session to understand the progress
Select count(*) from taxdocumentjson j inner join TaxDocumentRow r on r.TAXDOCUMENTJSON = j.ID;

HOW TO CONNECT TO SQL FROM AX AND UPDATE HOW TO CONNECT TO EXTERNAL DATABASE FROM AX HOW TO UPDATE RECORDS IN SQL FROM AX : DYNAMICS AX X++ CODE

HOW TO CONNECT TO SQL FROM AX AND UPDATE
HOW TO CONNECT TO EXTERNAL DATABASE FROM AX
HOW TO UPDATE RECORDS IN SQL FROM AX

1) fIRST CREATE AN ODBC CONNECTION FROM THE SYSTEM TO CONNECT TO THE REQUIRED DATABASES.
// X++, Main method in a class.
static public void Main(Args _args)
{
    LoginProperty loginProperty;
    OdbcConnection odbcConnection;
    Statement statement;
    ResultSet resultSet;
    str sql, criteria;
    SqlStatementExecutePermission perm;
    ;

    // Set the information on the ODBC.
    loginProperty = new LoginProperty();
    loginProperty.setDSN("dsnName");
    loginProperty.setDatabase("databaseName");

    //Create a connection to external database.
    odbcConnection = new OdbcConnection(loginProperty);

    if (odbcConnection)
    {
        sql = "SELECT * FROM MYTABLE WHERE FIELD = "
            + criteria
            + " ORDER BY FIELD1, FIELD2 ASC ;";

        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(sql);
        perm.assert();

        //Prepare the sql statement.
        statement = odbcConnection.createStatement();
        resultSet = statement.executeQuery(sql);

        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (resultSet.next())
        {
            //It is not possible to get field 3 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print resultSet.getString(1);
            print resultSet.getString(3);
        }

        //Close the connection.
        resultSet.close();
        statement.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC.");
    }
}

Saturday, April 16, 2016

DYNAMICS AX X++ CODE TO CONNECT TO SQL DATABASE DSN ODBC CONNECTION LOGIN

How  to connect to an external DB from Dynamics AX using X++


1. Create a DSN
To create a Data Source Name (DSN) go to Administrative Tools > Data Sources (ODBC).
Create the DSN on the tier where the X++ code will call the DSN from
2. X++ code
static void TestOdbcJob()
{
    LoginProperty login;
    OdbcConnection con;
    Statement stmt;
    ResultSet rs;
    str strQuery, criteria;
    SqlStatementExecutePermission perm;
    ;

    // Set the information on the ODBC.
    login = new LoginProperty();
    login.setDSN("dsnName");
    login.setDatabase("databaseName");

    //Create a connection to external database.
    con = new OdbcConnection(login);

    if (con)
    {
        strQuery = strfmt("SELECT * from tableName WHERE XXX = ‘%1′ ORDER BY  FIELD1, FIELD2", criteria);

        //Assert permission for executing the sql string.
        perm = new SqlStatementExecutePermission(strQuery);
        perm.assert();

        //Prepare the sql statement.
        stmt = con.createStatement();
        rs = stmt.executeQuery(strQuery);
       
        //Cause the sql statement to run,
        //then loop through each row in the result.
        while (rs.next())
        {
            //It is not possible to get field 2 and then 1.
            //Always get fields in numerical order, such as 1 then 2 the 3 etc.
            print rs.getString(1);
            print rs.getString(2);
        }


        rs.close();
        stmt.close();
    }
    else
    {
        error("Failed to log on to the database through ODBC");
    }
}

SQL CODE TO SCHEDULING SQL BACKUP SCHEDULING

SQL CODE TO SCHEDULING SQL BACKUP SCHEDULING

SQL CODE TO SCHEDULING SQL BACKUP SCHEDULING
vikas mehta

DECLARE @FOLDERPATH VARCHAR(500)

DECLARE @FOLDERPATHWITHNAME VARCHAR(500)

Declare @NAME Varchar(200)

Declare @DATE Varchar(200)

Declare @TIME Varchar(200)

Declare @TIME1 Varchar(200)

--JUST NEED TO UPDATE BELOW PATH FOR DB BACKUP LOCATION

Set @FOLDERPATH = '\\path\'

select @TIME1 = Convert(time, getdate())

select @DATE = (select convert(varchar,getDate(),112))

select @TIME = ((select Convert(Varchar, DATEPART(mm, @TIME1))) + (Select CONVERT(Varchar, DATEPART(ss, @TIME1))))

Select @NAME = ax + '_' + @DATE --+ @TIME

Set @FOLDERPATHWITHNAME = @FOLDERPATH + @NAME + '.bak'

BACKUP DATABASE [ax] TO DISK = @FOLDERPATHWITHNAME WITH NOFORMAT, NOINIT, NAME = @NAME, SKIP, NOREWIND, NOUNLOAD, STATS = 10

**********script*******************************
USE [msdb]
GO

/****** Object:  Job [Ax Prod Backup Schedule]    Script Date: 6/12/2015 3:17:03 PM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [[Uncategorized (Local)]]    Script Date: 6/12/2015 3:17:03 PM ******/
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'Ax Prod Backup Schedule',
                                @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'vikasvikas\axaosadmin', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Ax prod Step 1]    Script Date: 6/12/2015 3:17:04 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Ax prod Step 1',
                                @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'DECLARE @FOLDERPATH VARCHAR(500)

DECLARE @FOLDERPATHWITHNAME VARCHAR(500)

Declare @NAME Varchar(200)

Declare @DATE Varchar(200)

Declare @TIME Varchar(200)

Declare @TIME1 Varchar(200)

--JUST NEED TO UPDATE BELOW PATH FOR DB BACKUP LOCATION

Set @FOLDERPATH = ''\\sql bkup\''

select @TIME1 = Convert(time, getdate())

select @DATE = (select convert(varchar,getDate(),112))

select @TIME = ((select Convert(Varchar, DATEPART(mm, @TIME1))) + (Select CONVERT(Varchar, DATEPART(ss, @TIME1))))

Select @NAME = ''MicrosoftDynamicsAX'' + ''_'' + @DATE --+ @TIME

Set @FOLDERPATHWITHNAME = @FOLDERPATH + @NAME + ''.bak''

BACKUP DATABASE [MicrosoftDynamicsAX] TO DISK = @FOLDERPATHWITHNAME WITH NOFORMAT, NOINIT, NAME = @NAME, SKIP, NOREWIND, NOUNLOAD, STATS = 10

',
                                @database_name=N'master',
                                @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'AX 2012 Prod Job Schedule',
                                @enabled=1,
                                @freq_type=4,
                                @freq_interval=1,
                                @freq_subday_type=1,
                                @freq_subday_interval=0,
                                @freq_relative_interval=0,
                                @freq_recurrence_factor=0,
                                @active_start_date=20150421,
                                @active_end_date=99991231,
                                @active_start_time=235900,
                                @active_end_time=235959,
                                @schedule_uid=N'cddf7f74-3c12-414c-ab66-c12b7bc4628f'
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:
Related Posts Plugin for WordPress, Blogger...