Thursday, January 2, 2014

Create a Query in the AOT by Using X++


The following procedure is a job that you can run in the AOT to create a query called MyQuery, provided MyQuery does not already exist in the Queries node.



  1. In the AOT, right-click Jobs, and then click New Job. The Code editor window opens.
  2. In the Code editor window, copy the following code, and then paste it in the Code editor.

static void CreateQuery6Job(Args _args)
{
    TreeNode                treeNodeObj;
    Query                   queryObj; // Extends TreeNode class.
    QueryBuildDataSource    qbds;
    QueryBuildRange         qbr;
    QueryRun                qr;
    CustTable               xrecCustTable;
    str                     queryName = "MyQuery";
    
    // Macro.
    #AOT

    // Delete the query from the AOT, if the query exists.
    treeNodeObj = TreeNode::findNode(#QueriesPath);
    treeNodeObj = treeNodeObj.AOTfindChild(queryName);
    if (treeNodeObj) { treeNodeObj.AOTdelete(); }

    // Add the query to the AOT.
    treeNodeObj = TreeNode::findNode(#QueriesPath);
    treeNodeObj.AOTadd(queryName);
    queryObj = treeNodeObj.AOTfindChild(queryName);
    
    // Further define the query.
    qbds  = queryObj.addDataSource(tablenum(CustTable));
    qbr   = qbds.addRange(fieldnum(CustTable, DlvMode));
    qbr.value(">10");

    // Compile the query.
    queryObj.AOTcompile(1);
    queryObj.AOTsave();

    // Run the query.
    qr = new QueryRun("MyQuery");
    while ( qr.next() )
    {
        xrecCustTable = qr.GetNo(1); // 1 means first data source.
        Global::info(strFmt("%1 , %2",
            xrecCustTable.AccountNum, xrecCustTable.DlvMode));
    }        

    // Delete the query from the AOT.
    treeNodeObj = TreeNode::findNode(#QueriesPath);
    treeNodeObj = treeNodeObj.AOTfindChild(queryName);
    treeNodeObj.AOTdelete();
}

Press F7 to compile, and then press F5 to run the job. A query named MyQuery is created in the Queries node. The query is run, and then is deleted.

No comments:

Post a Comment