The X++ language used in Microsoft Dynamics 365 for Finance and Supply Chain has support for working with data. While it should almost never be done, there is a way to call SQL in X++ code. Using X++ queries is the preferred method for security reasons. That said, there may be a few special cases where a developer decides to call SQL code directly. In this article, I will explain how to call SQL code in X++, along with some examples of when using this ability may be helpful.
ExecuteUpdate Example
Before explaining how to call SQL in X++ code it is helpful to see a basic example. Review this example:
internal final class tutorialTSQL_ExecuteUpdate
{
public static void main(Args _args)
{
str sql;
int numRecordsAffected;
SqlStatementExecutePermission permission;
Connection conn = new Connection();
Statement statement;
sql = "delete from ecoresproductcategory where Product in (5637423123,5637423456,5637423789,5637423234,5637423555);";
info(strFmt(sql));
permission = new SqlStatementExecutePermission(sql);
permission.assert();
statement = conn.createStatement();
numRecordsAffected = statement.executeUpdate(sql);
info(strFmt("Number of records affected %1", numRecordsAffected));
// the permission needs to be reverted back.
CodeAccessPermission::revertAssert();
}
}

There are several other ways to write this code. However, to help learn this code, I want to start with a basic example before showing some slightly better versions of writing this type of code.
Next, I will explain each step of recreating this example from start to finish.
Runnable Job
Importantly, it is a best practice that code that updates or retrieves data is written using X++ code. Therefore, when you call SQL in X++ code, you will typically write it as part of a runnable job that you plan to run once as a custom script.
See this article for how to write a runnable class/job.
After completing the runnable job, see this article for how to deploy it to a TEST or Production environment as a custom script.
The code to call SQL in X++ is the same whether you have it in a runnable class or a regular class. However, most of the time it is expected that developers will only call SQL in a one-time custom script.
SQL Code
Next, write the SQL code you wish to run, and store that code in a string. For example:
str sql;
sql = "delete from ecoresproductcategory where Product in (5637423123,5637423456,5637423789,5637423234,5637423555);";
The syntax of writing SQL is different from X++ select statements. To learn how to write this code, see the great tutorials on W3Schools here.
SQLStatementExecutePermission
Next, before you can call SQL in X++ you need to check for permission to make this call. Since calling SQL directly can be dangerous, it is necessary that a developer explicitly tells the system when they are doing it, and when they have finished.
This involves creating a SqlStatementExecutePermission object, passing it the SQL statement you plan to run, and finally calling the ‘assert’ method. See this example.
SqlStatementExecutePermission permission;
permission = new SqlStatementExecutePermission(sql);
permission.assert();
To learn more about the SQLStatementExecutePermission class see this Microsoft documentation.
Create A Connection
Next, write X++ to create a connection to the underlying SQL database of the Microsoft Dynamics 365 F&SC system. The good news is that we don’t have to know the connection information. The system itself knows this information already. See these lines of code.
Connection conn = new Connection();
Statement statement;
statement = conn.createStatement();
Calling The SQL Code
After writing the SQL code, getting permission to call it, and creating a connection, the next step is to actually call SQL in X++.
Importantly, review whether your statement will retrieve data, or simply change data. If your code inserts, updates, or deletes data, use the ‘executeUpdate‘ method. If your code selects data, use the ‘executeQuery‘ method.
The example shown previously runs a ‘delete’ statement. Therefore, the code needs to call ‘executeUpdate’. See these lines of code.
int numRecordsAffected;
numRecordsAffected = statement.executeUpdate(sql);
info(strFmt("Number of records affected %1", numRecordsAffected));
Notice, calling ‘executeUpdate’ will return the number of records that were affected. Store this in an integer variable, and then use this in logs or messages when it makes sense.
Revert CodeAccessPermission
Lastly, it is important to revert the permission granted to call SQL in X++. Add this line of code after running the statement.
// the permission needs to be reverted back.
CodeAccessPermission::revertAssert();
See this Microsoft documentation for more information.
ExecuteQuery Example
In addition to calling ‘executeUpdate’, the other way to call SQL in X++ is to call ‘executeQuery’. This method should be used when you need to select data.
Here is an example of calling executeQuery, not to be confused with the ‘executeQuery‘ method on a DataSource.
internal final class tutorialTSQL_ExecuteQuery
{
public static void main(Args _args)
{
SqlStatementExecutePermission permission;
str sqlStatementText = "SELECT top 10 AccountNum FROM CustTable;";
permission = new SqlStatementExecutePermission(sqlStatementText);
permission.assert();
// Create a connection to the SQL Server
var connection = new Connection();
// Create a statement and submit the sql statement to the server:
Statement statement = connection.createStatement();
var resultSet = statement.executeQuery(sqlStatementText);
// Loop through results (columns are 1-indexed)
while (resultSet.next())
{
info(resultSet.getString(1));
}
// Revert the code access permission
CodeAccessPermission::revertAssert();
}
}

Notice, instead of returning the number of records affected, executeQuery returns a result set.
First, use a next() method and a while loop to iterate through each row of the result set.
Next, one option is to use a method like ‘getString(1)‘, specifying the column number within that row, to retrieve the value of a field on that row.
SQL Injection
Some of the examples above use ‘where clauses’ to filter the results of the query. In those examples, the text is hard coded, meaning the user cannot change the query that gets run. That said, there may be times that you want to use a variable in your query, which creates the possibility of SQL injection.
Again, it is not recommended that you call direct SQL except in very specific cases. Even then, it is recommended you specify the exact SQL code to run. That said, assuming you have a very good reason you need to call direct SQL, I want to explain how you would do it safely.
SQL injection happens when someone passes data to the SQL string that causes it to behave in a destructive or dangerous way.
For example, consider this code:
public void GetAccountNum(str custGroup)
{
str sqlStatementText = "SELECT top 10 AccountNum FROM CustTable where custGroup = '" + custGroup + "'";
...
}
To explain, the code dynamically passes in the customer group so that customers in a different group can be returned. This works fine if a value like ’10’ is passed in.
However, what happens if the custGroup variable can be set by the user, and the user passes in a value set to:
'; drop table CustTable --
The system would end up running this SQL query:
SELECT top 10 AccountNum FROM CustTable where custGroup = ”; drop table CustTable –‘
This code could potentially drop the table in the database. Therefore, whenever we allow input from a user or code to change the SQL query, we need to use safer methods.
This is the code for the full example:
internal final class tutorialTSQL_ExecuteQuery_Parameters
{
public static void main(Args _args)
{
tutorialTSQL_ExecuteQuery_Parameters tutorialTSQL_ExecuteQuery_Parameters = new tutorialTSQL_ExecuteQuery_Parameters();
tutorialTSQL_ExecuteQuery_Parameters.GetAccountNum("10");
}
public void GetAccountNum(str custGroup)
{
str sqlStatementText = "SELECT top 10 AccountNum FROM CustTable where custGroup = '" + custGroup + "'";
SqlStatementExecutePermission permission;
permission = new SqlStatementExecutePermission(sqlStatementText);
permission.assert();
// Create a connection to the SQL Server
var connection = new Connection();
// Create a statement and submit the sql statement to the server:
Statement statement = connection.createStatement();
var resultSet = statement.executeQuery(sqlStatementText);
// Loop through results (columns are 1-indexed)
while (resultSet.next())
{
info(resultSet.getString(1));
}
// Revert the code access permission
CodeAccessPermission::revertAssert();
}
}
ExecuteQueryWithParameters
Importantly, if you call SQL in X++ and you need to pass a parameter, use the method ‘executeQueryWithParameters’ to mitigate the threat of SQL injection.
See this example code that uses ‘executeQueryWithParameters‘:
internal final class tutorialTSQL_ExecuteQueryWithParameters
{
public static void main(Args _args)
{
tutorialTSQL_ExecuteQueryWithParameters tutorialTSQL_ExecuteQueryWithParameters = new tutorialTSQL_ExecuteQueryWithParameters();
tutorialTSQL_ExecuteQueryWithParameters.GetAccountNum("10");
}
public void GetAccountNum(str custGroup)
{
str sqlStatementText = "SELECT top 10 AccountNum FROM CustTable where custGroup = @CustGroup";
SqlStatementExecutePermission permission;
permission = new SqlStatementExecutePermission(sqlStatementText);
permission.assert();
// Create a connection to the SQL Server
var connection = new Connection();
// Create a statement and submit the sql statement to the server:
Statement statement = connection.createStatement();
// Create a mapping from parameter names onto values
Map paramMap = SqlParams::create();
paramMap.add('CustGroup', custGroup);
var resultSet = statement.executeQueryWithParameters(sqlStatementText, paramMap);
// Loop through results (columns are 1-indexed)
while (resultSet.next())
{
info(resultSet.getString(1));
}
// Revert the code access permission
CodeAccessPermission::revertAssert();
}
}

Importantly, the method executeQueryWithParameters takes a second parameter, which is a map of parameters.
Now, if bad SQL code were passed into the ‘custGroup’ variable, the executeQueryWithParameters method would treat it as a plain value, so the query would simply find no matching customers instead of running the injected command.
ExecuteUpdateWithParameters
Similarly, the executeUpdateWithParameters method should be used whenever the SQL code you write is modifying data, and takes parameters.
See this example:
internal final class tutorialTSQL_ExecuteUpdateWithParameters
{
public static void main(Args _args)
{
tutorialTSQL_ExecuteUpdateWithParameters tutorialTSQL_ExecuteUpdateWithParameters = new tutorialTSQL_ExecuteUpdateWithParameters();
tutorialTSQL_ExecuteUpdateWithParameters.UpdateCustomerGroup("004003", "10");
}
public void UpdateCustomerGroup(str accountNum, str custGroup)
{
int numRecordsAffected;
str sqlStatementText = "Update CustTable set custGroup = @CustGroup where accountNum = @AccountNum";
SqlStatementExecutePermission permission;
permission = new SqlStatementExecutePermission(sqlStatementText);
permission.assert();
// Create a connection to the SQL Server
var connection = new Connection();
// Create a statement and submit the sql statement to the server:
Statement statement = connection.createStatement();
// Create a mapping from parameter names onto values
Map paramMap = SqlParams::create();
paramMap.add('CustGroup', custGroup);
paramMap.add('AccountNum', accountNum);
numRecordsAffected = statement.executeUpdateWithParameters(sqlStatementText, paramMap);
info(strFmt("Number of records affected %1", numRecordsAffected));
// Revert the code access permission
CodeAccessPermission::revertAssert();
}
}


For more information, see the Microsoft documentation.
Further Improvements
Finally, there are a few potentially even better ways to specify the name of the table or fields when working with direct SQL code. Instead of hard-coding the name of a table, or the column order, the DictTable class can be used to find and use the name.
Because direct SQL is typically planned to run once as part of a runnable job to make a change that can’t be done using an X++ query, it may be sufficient to hard code the name of the fields. But if you want to go even further, here is an example:
internal final class tutorialTSQL_ExecuteQueryWithParametersComplete
{
server static void main(Args _args)
{
DictTable dictTable;
Connection connection;
Statement statement;
str sql;
ResultSet resultSet;
SqlStatementExecutePermission perm;
dictTable = new DictTable(tableNum(CustTable));
str custGroup = "10";
if (dictTable != null)
{
connection = new Connection();
sql = strfmt("SELECT top 10 %1 FROM %2 where %3 = @CustGroup",
dictTable.fieldname(fieldnum(CustTable, SalesGroup), DBBackend::Sql),
dictTable.name(DbBackend::Sql),
dictTable.fieldname(fieldnum(CustTable, CustGroup), DBBackend::Sql)
);
perm = new SqlStatementExecutePermission(sql);
// Check for permission to use the statement.
perm.assert();
statement = connection.createStatement();
// Create a mapping from parameter names onto values
Map paramMap = SqlParams::create();
paramMap.add('CustGroup', custGroup);
resultSet = statement.executeQueryWithParameters(sql, paramMap);
// Loop through results (columns are 1-indexed)
while (resultSet.next())
{
info(resultSet.getString(1));
}
// End the scope of the assert call.
CodeAccessPermission::revertAssert();
}
}
}

Create an Index
Most or all of the examples shown so far could be done using regular X++ code. However, the ability to call SQL in X++ is very helpful when you need to create an index on a table or update statistics.
Typically you should make the index change in the Application Explorer, and then promote the change by applying a package to the environment.
However, if you are experiencing performance issues and need an immediate fix, you can write a runnable job that runs SQL, and upload the code as a custom script.
Here is an example:
internal final class tutorialTSQL_CreateIndex
{
public static void main(Args _args)
{
Connection connection;
Statement statement;
str sql;
SQLStatementExecutePermission permission;
try
{
sql = 'CREATE INDEX [I_JournalNum] ON [dbo].[MyCustomTable] (partition, dataareaId, journalnum);
CREATE INDEX [I_Processed] ON [dbo].[MySecondCustomTable] (partition, dataareaId, processed);
UPDATE STATISTICS SALESTABLE;
UPDATE STATISTICS SALESLINE;';
connection = new Connection();
statement = connection.createStatement();
new SqlStatementExecutePermission(sql).assert();
statement.executeUpdate(sql);
CodeAccessPermission::revertAssert();
Info("Completed.");
}
catch
{
Global::exceptionTextFallThrough();
}
}
}
Please see this article by my friend Jeff Rizzi for more information.

Conclusion
Importantly, whenever possible you should use X++ when selecting or changing data in Microsoft Dynamics 365 F&SC. However, there may be a few small exceptions where running direct SQL code against the database may be necessary. In this article you learned how to call SQL in X++ using executeQuery, executeUpdate, executeQueryWithParameters, and executeUpdateWithParameters. Additionally, you learned how to assert the SqlStatementExecutePermission to allow direct SQL to be run.
Leave a Reply