AXForum  
Вернуться   AXForum > Microsoft Dynamics AX > DAX Blogs
DAX
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 16.04.2008, 02:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
gatesasbait: Dynamics Ax SQL statements (SQL Strings in DAx)
Источник: http://gatesasbait.spaces.live.com/B...B9F5!206.entry
==============


Good afternoon,

Yesterday I hit a snag, took me a few hours to figure out (!). I had tinkered with SQL strings in ReleaseUpdate classes often before, tweaking them, rewriting them for optimization etc... but I don't recall ever writing up a new class that needed to run SQL Statements as strings. Yesterday I needed to do that because a customer wanted a report that would display some data accross all companies in an instance. Using the 'changecompany' keyword proved to be heavily inefficient since all data was in the same table and I only had to group by fields accros companies on the one table.

After fighting for a few minutes trying to fool QueryBuildRanges to span multiple DataAreaIds, or trying to change the company on a QueryBuildDataSource at runtime, I decided to use an SQL string.

But the issue I had is that the calling context for SQL Statement execution has to be RUN ON SERVER. The solution was to create a new class, a main() and a menuitem running it. Here is a sample of a class executing an SQL statement (obviously not my customer's!). It returns the customer Id for all customers accross all DataAreaIds (companies) on a database instance; whereas a standard select only returns the customers for the current company (curext()).

X++:
public class MySQLTest
{
    //AOSRunMode::Server
}
 
public static server void main(Args args)
{
    Connection  connection = new Connection();
    Statement   stmt = connection.createStatement();
    SqlSystem   sqlSystem = new SqlSystem();
    str         sqlStmt;
    int         i;
    ResultSet   resultSet;
    SqlStatementExecutePermission   sqlStatementExecutePermission;
    ;
 
    sqlStmt =  'SELECT * ';
    sqlStmt += 'FROM CustTable';
    sqlStatementExecutePermission = new SqlStatementExecutePermission(sqlStmt);
    sqlStatementExecutePermission.assert();
 
    resultSet = stmt.executeQuery(sqlStmt);
 
    while (resultSet.next())
    {
        info(resultSet.getString(1));
    }
}
The //AOSRunMode::Server marker is only for the BP checker. You can either specify 'server' on the static method declaration or as a property on the calling menuitem.


Источник: http://gatesasbait.spaces.live.com/B...B9F5!206.entry
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
Старый 16.04.2008, 06:55   #2  
mazzy is offline
mazzy
Участник
Аватар для mazzy
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
29,472 / 4494 (208) ++++++++++
Регистрация: 29.11.2001
Адрес: Москва
Записей в блоге: 10
Цитата:
Сообщение от Blog bot Посмотреть сообщение
After fighting for a few minutes trying to fool QueryBuildRanges to span multiple DataAreaIds, or trying to change the company on a QueryBuildDataSource at runtime, I decided to use an SQL string.
На мой взгляд, еще один типичный пример бездумного программирования.

Человек начал писать прямые запросы вместо того, чтобы разобраться с причиной "нехотения" Аксапты делать запрос не нескольким компаниям.

В результате написал запрос который действительно работает по ВСЕМ компаниям.
Но при этом его запрос полностью игнорирует настройки виртуальных компаний и RLS.

Кроме того, теперь ему придется потратить не несколько минут, а несколько часов чтобы собрать запись CustTable при помощи getString'ов из resultSet.

Кроме того, человек совершенно не подумал о будущем: в запросе он выбирает все поля звездочкой, а выборку делает по НОМЕРУ поля. Бог с ней, с производительностью Но что произойдет, когда когда-нибудь кто-нибудь добавит поля в СЕРЕДИНУ записи! Например, купит и добавит еще одну финансовую аналитику. С огромной вероятностью этот его код, получающий данные по номеру поля перестанет работать...

Ждем от автора яростных статей на тему "глючности" Аксапты. Но может быть автор напишет более конструктивно на тему преобразований из строки, на тему производительности, а может быть даже на тему виртуальных компаний.
__________________
полезное на axForum, github, vk, coub.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Dynamics AX: Why upgrade to SQL Server 2008 with DAX 2009? Blog bot DAX Blogs 0 16.10.2008 06:24
axStart: Microsoft Dynamics AX 2009 Hot Topics Web Seminar Series Blog bot DAX Blogs 0 06.08.2008 12:05
Dynamics AX: Dynamics AX 2009 & SQL Server 2008 Blog bot DAX Blogs 0 10.06.2008 21:08
gatesasbait: Local DAX installation method also works for Dynamics Ax 5.0 Build 366 Blog bot DAX Blogs 0 28.11.2007 18:51
Dynamics AX: SQL Server, Heart of Dynamics AX Blog bot DAX Blogs 0 13.07.2007 18:00

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 09:00.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.