Tag Archives: SQL

Exceptions Inside Transactions

When an exception is thrown inside a transaction, the transaction is automatically aborted (a ttsabort operation occurs). This applies both for exceptions thrown manually and for exceptions thrown by the system.

If an exception is thrown inside a ttsBegin/ttsCommit block, it will be caught by the first matching catchlist that is outside the transaction block. If there is a catch block within the ttsBegin/ttsCommit, it will be ignored



Example  shows how an exception in a ttsBegin/ttsCommit block is caught by the first catchlist outside the block rather than by the catch within the ttsBegin/ttsCommit block. If you run this code, “outside tts” will be printed before an Infolog displays “Message”.






throw error(“Message”);




print “not here”;







print “outside tts”;






Posted by on January 20, 2011 in AX, Basics, Dynamics, SQL, Tables, X++


Tags: , , , , , ,

Fetching Records Using Query Object

In my previous post “Playing with data”, I have made you guys learn how to retrieve data using the select query which you can write anywhere. You just need to declare the table buffer for that. However, there are some cases where it is not recommended to use the select statement to retrieve data for example it is not recommended to use select statement at Form level methods. So, what could be used to retrieve data? The answer is Using Query Object. Normally queries are stored in AOT (see Queries Node in AOT), but they can also

be created from code dynamically. The Query object is used when a user interaction is required, like user wants to add range or sort the data.

In order to create query from code, the objects that needs to be created are,

  • Query:

    The query class object defines the structure of the query. Objects of this type are not used for fetching records from the database. Instead, use a QueryRun object that may be assigned a query object.


  • QueryBuildDataSource :

    The QueryBuildDataSource class provides the building blocks that queries are made of. It holds the tables that needed to be added in the query. The hierarchy of the datasources of query are defined in this object. Like if query has a join with another table, so child table is added using the QueryBuildDatasource object of parent table.


  • QueryRun:

    The QueryRun class traverses tables in the database while fetching records that satisfy constraints given by the user, and helps gather such constraints from user input.



The object to add the range to the query is,

  • QueryBuildRange:

    The QueryBuildRange class represents the ranges that define which records should be fetched from the data source in which the QueryBuildRange is associated. The value property can be used to set the string that defines the range.



Now, lets have a code example how to use the objects of these classes. Create a new job and add the following code.


static void CustTableSales(Args _args)


Query query;

QueryBuildDataSource qbds1;

QueryBuildDataSource qbds2;

QueryBuildRange qbr1;

QueryBuildRange qbr2;

QueryRun queryRun;

CustTable custTable;


query = new Query();

qbds1 = query.addDataSource(tablenum(CustTable));

qbr1 = qbds1.addRange(fieldnum(CustTable, Blocked));


qbr2 = qbds1.addRange(fieldnum(CustTable, CustGroup));


qbds2 = qbds1.addDataSource(tablenum(SalesTable));


qbds2.addLink(fieldnum(CustTable, AccountNum), fieldnum(SalesTable, CustAccount));


queryRun = new QueryRun(query);

while (


custTable = queryRun.get(tablenum(CustTable));

info(strfmt(“%1 – %2”,custTable.Name,






This job runs the query that selects all active customers who belong to group 10 and have at least one sales order. To set the range value a global function “queryValue(anyType _anyType)” is used which takes a value of any type. There is another static function in the SysQuery class, e.g SysQuery::value().

If the addRange method is called for same field then an OR is added to where clause and if the addRange is called for different field the AND is added to the where clause in the query.

To add OR in the where clause in different field, you can make the expression using the strfmt() global function as,


qbr2.value(strfmt(‘((%1 = “%2”) || (%3 = “%4”))’,






Yes, you can make the expression as you like using the strfmt(), you can use greater than, less than in the query as,

qbr3.value(strFmt(‘(ModifiedDate > %1)’, Date2StrXpp(01012000)));


One thing which should be noted here is the use of Date2StrXpp() global function. It is really a need for a range on date field to use this function. Without this function the query will not be executed correctly and wrong results will be displayed. So, whenever there is a need of applying range on Date field use Date2StrXpp() function.


There are a lot to discuss about query, which cannot be covered in a single post. And it will be boring if I mention everything about query in single post. So wait for new post to explore more about Query Object.

Thanks guys, comments and suggestion will be appreciated.

Leave a comment

Posted by on July 30, 2010 in AX, Dynamics, SQL, Tables, X++


Tags: , , , , ,

Playing with data

In this post, I am going to discuss about how the data can be retrieved, created, updated or deleted using data access and manipulating functionality provided by Dynamics AX framework. In DAX, developer doesn’t need to worry about opening the database connection, make transaction or fetching data, and close the connection. Rather doing these steps DAX framework requires only the table buffer variable to make transaction or manipulating data. What is table buffer? Hmmm, a table buffer is a variable of any Table which stores complete records, for example you can access any field of the table using that variable. Let’s take a simple example. In the Table node of the AOT, we have a table called “CustTable”, now we can declare a table buffer as,


CustTable custTable; ///table buffer variable of table type “CustTable”


A table buffer must be declared before using the select statement to retrieve data. The select statement is based on the SQL standard and quite similar to SQL server query statement except the fact that joining is little different for example there is no “ON” keyword in X++. The developer having experience in LINQ won’t have a problem in understanding the working of data access implementation in DAX. See the below simple job and its result.


static void Select_Statement(Args _args){

CustTable custTable;

select firstOnly custTable;

print custTable.AccountNum + ” ” + custTable.CustGroup;



And the result after running this job is, 


Now lets analyze the job, firstly a table buffer of table CustTable is declared, and in the 2nd line a select statement is written with the keyword “firstonly” which retrieves only one record based on the primary index defined on the Table. The “firstonly” keyword called the find option in DAX. The other find option keywords are “forUpdate”, “noFetch”, “firstFast”, and “reverse”. You can also define multiple find option keyword within a single select statement. A field list can also be provided with the select statement with the keyword “from”, for example,  

select firstoOnly AccountNum, CustGroup from custTable;  

Note: its now the BP error if not define the field list in the select statement in the AX 6.0 version.

Can we fetch multiple records? Yes, we can fetch multiple records using the “while” keyword with the select statement. The while loop will continue until all the records is fetched based on the condition in the where clause of the select statement. If now condition is defined, the loop will execute till the last record. 

See and observe the output of the following job. 

static void Select_Statement(Args _args){CustTable custTable;

while select AccountNum, custGroup from custTable

where custTable.CustGroup == “40”


print custTable.AccountNum + ” ” + custTable.CustGroup;





Aggregate functions like sum, count, avg etc. can be used in the select statement like,  

select count(AccountNum) from custTablegroup by custTable.CustGroupwhere custTable.CustGroup == “40”;

print custTAble.AccountNum;


Lets talk about “joins” in DAX, how we can join multiple tables in the select statement. See the below simple example of join, which joins custTable with custGroup table. 

static void Select_Join_Statement(Args _args){CustTable custTable;

CustGroup custGroup; 

while select * from custTable

join * from custGroup

where custTable.CustGroup == custGroup.CustGroup

&& custGroup.Name == “Wholesalers”


print custTable.AccountNum + ” ” + custTable.Currency + ” ” + custGroup.PaymTermId;




Instead of “On” keyword “where” keyword is used to join the same field of the tables that needs to be joined. The Join can be of type “Inner”, “outer”, “exists”, and “not exists”. There is no inner keyword so if the keyword join is written without the other keyword is referred to as inner join. See the below explanation of join types,

Join Type Explanation
join Fetches the records that matches on both the table. It is the inner join.
outer join Fetches the records whether or not records matches on both the table.
exists join Fetches record from the table define before the exists keyword that matches with the records in the 2nd table. No records will be fetched from thesecondary table using exists join.
notexists join Opposite of exists join. Will fetch records from the primary table, where norecords in the secondary table match the join expression.


Try and observe the join type result by creating a job. 

Now lets talk about insert, update, and delete records from the table. These will also be done by using the table buffer. In the table buffer, we have methods, of insert, update , and delete. To insert a record into table, declare table buffer, set values of the fields and call insert method of that table buffer. For example, 

static void Insert_Job(Args _args){

CustTable custTable;

custTable.AccountNum = “4444”;

custTable.Currency = “USD”;



Similarly, to update the record, update method will be called, but first records need to be fetched using the select statement with the keyword “forupdate”. 

static void Update_Job(Args _args){

CustTable custTable;

select forupdate * from custTable where custTable.AccountNum == “4444”; 

custTable.Currency = “EUR”;



You can also update the record using the statement “update_recordset

update_recordset custTablesetting currency = “EUR”where custTable.AccountNum ==”4444″;


Now to delete the record, you can delete the record in two ways, either fetch the record using the forupdate keyoword and call the delete method of table buffer or using the delete_from statement.

static void Delete_Job(Args _args){

CustTable custTable;

forupdate * from custTable where custTable.AccountNum == “4444”;



Or using delete_from like,

delete_from custTablewhere custTable.AccountNum ==”4444″;

Inserting, updating, and deleting records are placed under the ttsbegin; and ttscommit; block. These keywords are usually placed to make sure that the transactions to database have been done successfully. If any failure occurs during the transaction then the state will be roll back to position before the ttsbegin keyword. ttsabort; keyword is also used when any exception occurs and transaction needs to be aborted.

 Thanks for reading.


Posted by on April 16, 2010 in Basics


Tags: , , , ,