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

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 17.08.2010, 22:06   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
dynamicsaxtraining: Select statement patterns
Источник: http://www.dynamicsaxtraining.com/ti...ement-patterns
==============

This article contains descriptions of select statement patterns that can be used in the Microsoft Dynamics AX (Axapta).

The list of select statement patterns provided is as follows:
  1. Enable/Disable condition
  2. Switch condition
  3. Enable/Disable join table with condition
Enable/Disable Condition

Use this pattern when the condition in the “where” clause is dependant of a parameter.
For example, we need to perform some procedure with either all Customer or Customers with invoice account only. It depends on the User input parameter. We create a periodic job with the following dialog box:

Process Customers


We will assume that the Customer with invoice account check box has the dialogField name in the code.

The select statement will have the following view in the “run” method:

X++:
while select custTable
where (!dialogField.value() || custTable.InvoiceAccount != '')
If the check box is selected, !dialogField.value() returns false and custTable.InvoiceAccount != ” will be taken into account. If the check box isn’t selected, !dialogField.value() returns true (so there is no sense what return the custTable.InvoiceAccount != ” condition). In other words, if the check box is selected, only Customers with Invoice accounts will be searched. Otherwise, all Customers will be searched.

General structure looks as follows: where (!EnableConditionFlag || condition)

Switch Condition

Use this pattern when either one or another condition dependant of parameter must be applied to the select statement.

For example, we need to perform a procedure with items of either a BOM item or items of other item types. We need to create a periodic job with a dialog box. The dialog box contains only one BOM type checkbox. We will assume that the BOM type check box has the dialogField name in the code.

In the run method, we write the following select statement:

X++:
while select inventTable
where ((!dialogField.value() && inventTable.ItemType != ItemType::BOM) ||
       (dialogField.value()  && inventTable.ItemType == ItemType::BOM))
If the BOM type check box is selected, the first parenthesis returns false and everything depends on the second parenthesis where the inventTable.ItemType == ItemType::BOM clause is checked. If the BOM type check box isn’t selected, the second parenthesis returns false and everything depends on the first parenthesis where the inventTable.ItemType != ItemType::BOM clause is checked. In other words, if the check box is selected, the only BOM item will be searched. Otherwise, only not BOM items will be searched.

General structure looks as follows: where ((!Condition2Flag && condition 1) || (Condition2Flag && condition 2))

Enable/Disable Join Table with Condition

Use this pattern when a joined table with a condition can either contain records or be empty.

For example, we need select sales orders without Recipient or terminated Recipient. The SalesTaker field in the SalesTable table stores the Recipient ID. The Status field in the EmplTable table stores the Recipient’s status (None, Employed, or Resigned).

The select statement has the following view:

X++:
while select SalesTable
notexists join EmplTable
where EmplTable.EmplId == SalesTable.SalesTaker &&
      EmplTable.status != HRMEmplStatus::Resigned
If EmplTable.status is Resigned or the Sales table record doesn’t have the Recipient, the Sales table record will be selected.

General structure looks as follows: notexists join where && (condition != required value)

If you know other interesting patterns, please write them in the comments

Technorati Tags: select statement, select statement patterns, where clause



Источник: http://www.dynamicsaxtraining.com/ti...ement-patterns
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
Старый 18.08.2010, 01:05   #2  
Wamr is offline
Wamr
----------------
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
 
1,737 / 858 (32) +++++++
Регистрация: 15.01.2002
Адрес: Москва
Записей в блоге: 7
и главный pattern - не используйте эти patterns
используйте Query & QueryRun
За это сообщение автора поблагодарили: gl00mie (3).
Старый 18.08.2010, 12:16   #3  
Volodymyr is offline
Volodymyr
Участник
 
36 / 21 (1) +++
Регистрация: 03.11.2006
Адрес: Киев
Почему? Интересно что отработает быстрее Query или select?
Старый 18.08.2010, 12:32   #4  
lev is offline
lev
Ищущий знания...
Аватар для lev
Oracle
MCBMSS
Axapta Retail User
 
1,723 / 491 (20) +++++++
Регистрация: 18.01.2005
Адрес: Москва
Цитата:
Сообщение от Volodymyr Посмотреть сообщение
Почему? Интересно что отработает быстрее Query или select?
Одинаково должно отрабатывать по идее И то и другое отсылает сформированный запрос к базе.
Не один раз проводил тесты у себя, время выполнения всегда было идентично

Тут скорее вопрос в читаемости кода, и в удобности использования синтаксиса, и на мой взгляд, все зависит от ситуации
__________________
"Страх перед возможностью ошибки не должен отвращать нас от поисков истины." (с)
С Уважением,
Елизаров Артем
Старый 18.08.2010, 13:05   #5  
oip is offline
oip
Axapta
Лучший по профессии 2014
 
2,564 / 1416 (53) ++++++++
Регистрация: 28.11.2005
Записей в блоге: 1
Цитата:
If you need user interaction regarding the data you need processed, a query is the preferable way
__________________
С уважением,
Олег.
Старый 18.08.2010, 13:27   #6  
Volodymyr is offline
Volodymyr
Участник
 
36 / 21 (1) +++
Регистрация: 03.11.2006
Адрес: Киев
Спасибо! Вобщем то если это переменная не из юзер интерфейса, то можно использовать. Я например очень часто первым Enable/Disable пользуюсь.
Старый 18.08.2010, 14:44   #7  
gl00mie is offline
gl00mie
Участник
MCBMSS
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,684 / 5788 (200) ++++++++++
Регистрация: 28.11.2005
Адрес: Москва
Записей в блоге: 3
Подобные публикации так и побуждают понудеть...
Цитата:
Сообщение от Blog bot Посмотреть сообщение
X++:
while select custTable
where (!dialogField.value() || custTable.InvoiceAccount != '')
В игрушечных базах оно, может, и без разницы, но в реальной жизни было замечено, что оптимизатор запросов СУБД совершенно по-разному реагирует на условия вида custTable.InvoiceAccount != '' и custTable.InvoiceAccount > '' - по смыслу они вроде как идентичны, но оптимизатору запросов так почему-то не кажется. К слову, и само ядро, если в запросе указать просто custTable.InvoiceAccount (неявно приводя InvoiceAccount к булевскому типу), формирует запрос с условием > '', а не != ''.
Цитата:
Сообщение от Blog bot Посмотреть сообщение
X++:
while select SalesTable
notexists join EmplTable
where EmplTable.EmplId == SalesTable.SalesTaker &&
      EmplTable.status != HRMEmplStatus::Resigned
Вот это просто вошлебный пример! Фильтрация по неиндексированному полю SalesTable, да еще и с notexists join - вернейший способ получить полное сканирование таблицы с подзапросами к подчиненной таблице на каждую запись в SalesTable.
Цитата:
Сообщение от Blog bot Посмотреть сообщение
General structure looks as follows: notexists join where && (condition != required value)
Скорее general structure looks as follows: не используйте notexists join на сколь-нибудь больших выборках - зачастую тупо перебрать записи, или закэшировать данные из подчиненной таблицы, или использовать какой-нить RecordSortedList для избавления от дублирующихся по определенным критерями записей оказывается с точки зрения производительности намного предпочтительнее. Вот уж действительно:
Цитата:
Сообщение от Wamr Посмотреть сообщение
и главный pattern - не используйте эти patterns
используйте Query & QueryRun
За это сообщение автора поблагодарили: Wamr (3), Logger (5), oip (1), Volodymyr (1).
Старый 19.08.2010, 12:57   #8  
Volodymyr is offline
Volodymyr
Участник
 
36 / 21 (1) +++
Регистрация: 03.11.2006
Адрес: Киев
Привет. Кажется не туда копать стали.
Как по мне интерес представляет именно "шаблон", а не условие.
Структура первая, вида :

while
select custTable
where (!dialogField.value() || custTable.InvoiceAccount != '')

Позволяет включать выключать любое условие, а какое оно дело рук каждого.
Удобно и практично, ну можно и кверей никто не спорить.

Насчет notexists join опять же дело рук каждого.

Соглашусь что примере приведены не самые лучшие.
Но идея хорошая.

Старый 19.08.2010, 19:12   #9  
gl00mie is offline
gl00mie
Участник
MCBMSS
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,684 / 5788 (200) ++++++++++
Регистрация: 28.11.2005
Адрес: Москва
Записей в блоге: 3
Мне лично Query больше нравится тем, что:
  • можно разбить логику построения запроса на несколько методов, а их - выборочно перекрывать в различных классах-наследниках; для while select нужно либо переписывать запрос целиком, либо в базовом классе предусматривать все возможные условия в запросе и цеплять их тем способом, который был представлен (!flag || condition), что не прибавляет коду наглядности и понятности;
  • после добавления всех нужных условий по Query легко увидеть без включения трассировки, какой же в результате запрос получился;
  • Query можно передать в другой кусок кода, который не знает, как он был сформирован, а только знает, записи из какой таблицы нужно выбирать;
  • Query можно легко переделать для рассчета каких-нить агрегатов вместо перебора записей (бывает, люди хотят видеть на форме поле с суммой по всем записям, удовлетворяющим текущему запросу, - с Query это сделать проще простого);
  • в Query не надо извращаться, если какой-то datasource нужно цеплять только по определенному условию, потому что этому datasource'у можно сказать enabled(false) - и он уже не попадет в запрос;
  • при использовании Query по умолчанию включена RLS - в случае чего, не надо потом бегать и в куче мест дописывать перед запросом salesTable.recordLevelSecurity( true ).
Старый 20.08.2010, 00:37   #10  
Vadik is offline
Vadik
Модератор
Аватар для Vadik
Лучший по профессии 2017
Лучший по профессии 2015
 
3,631 / 1849 (69) ++++++++
Регистрация: 18.11.2002
Адрес: гражданин Москвы
Цитата:
Сообщение от gl00mie Посмотреть сообщение
Фильтрация по неиндексированному полю SalesTable, да еще и с notexists join - вернейший способ получить полное сканирование таблицы с подзапросами к подчиненной таблице на каждую запись в SalesTable
Я вам не скажу за всю Одессу, но на MSSQL not exists join давно уже вроде как разрешается через right anti semi join с разовым table\index scan-ом, не так уж все и страшно, как может показаться

Цитата:
Структура первая, вида :
X++:
while select custTable
where (!dialogField.value() || custTable.InvoiceAccount != '')
Позволяет включать выключать любое условие
Да, любое условие, прописанное разработчиком. А так как требования к продукту у нас обычно определяются уже на этапе тестирования, получаем в итоге бедного разработчика, осаждаемого парой-тройкой Петровичей с их безумными взаимоисключающими хотелками, монстроидальные формы и мостроидальные запросы. То ли дело Query - один раз пользоваться научил, сиди, твори спокойно
__________________
-ТСЯ или -ТЬСЯ ?
Старый 20.08.2010, 14:01   #11  
Wamr is offline
Wamr
----------------
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
 
1,737 / 858 (32) +++++++
Регистрация: 15.01.2002
Адрес: Москва
Записей в блоге: 7
вот к чему в конечном итоге приводит любовь к "хорошей идеи"
X++:
    while select
    sum(Qty), sum(costAmountPosted), sum(costAmountAdjustment) from InventTrans
    group by ItemId
    where
    (!itemId || InventTrans.ItemId == itemId)
    &&
    (
        (
            !dateFrom
            ||
            (
                InventTrans.DatePhysical > dateFrom
                ||
                (
                    isTime
                    &&
                    (
                        InventTrans.DatePhysical == dateFrom &&
                        (
                            InventTrans.GM_DatePhysical > dateFrom
                            ||
                            (
                                InventTrans.GM_DatePhysical == dateFrom &&
                                InventTrans.AX_TimePhysical >= timeFrom
                            )
                        )
                    )
                )
            )
        )
        &&
        (
            !dateTo
            ||
            (
                InventTrans.DatePhysical < dateTo
                ||
                (
                    isTime
                    &&
                    (
                        InventTrans.DatePhysical == dateTo &&
                        (
                            InventTrans.GM_DatePhysical < dateTo
                            ||
                            (
                                InventTrans.GM_DatePhysical == dateTo &&
                                InventTrans.AX_TimePhysical < timeTo
                            )
                        )
                    )
                )
            )
        )
    )
    &&
    (
        InventTrans.StatusReceipt == StatusReceipt::Purchased ||
        InventTrans.StatusReceipt == StatusReceipt::Received ||
        InventTrans.StatusIssue == StatusIssue::Sold ||
        InventTrans.StatusIssue == StatusIssue::Deducted
    )
    && InventTrans.TransType == InventTransType::Sales
    join salesTable group by GM_SalesOperationType where
    salesTable.SalesId == inventTrans.TransRefId
    join inventDim group by inventDimDefect where
    inventDim.inventDimId == inventTrans.inventDimId &&
    (!defect || inventDim.inventDimDefect == defect)
    exists join GM_CalcInventLocationOperational where
    dataAreaAdmin ||
    (!dataAreaAdmin && GM_CalcInventLocationOperational.InventLocationId == inventDim.InventLocationId)
    exists join GM_CalcInventLocationAdministrative where
    (
        (
            dataAreaAdmin &&
            GM_CalcInventLocationAdministrative.CalcInventLocation == GM_CalcInventLocation &&
            GM_CalcInventLocationAdministrative.InventLocationId == inventDim.InventLocationId
        )
        ||
        (
            !dataAreaAdmin &&
            GM_CalcInventLocationAdministrative.InventLocationId == GM_CalcInventLocationOperational.AdministrativeInventLocationId &&
            GM_CalcInventLocationAdministrative.CalcInventLocation == GM_CalcInventLocation
        )
    )
За это сообщение автора поблагодарили: fed (5), Lemming (5), gl00mie (2).
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
dynamicsaxtraining: Item setup: Inventory dimension group Blog bot DAX Blogs 1 05.10.2010 15:35
Rajdip's space: When using index (not using hint) in a select statement without 'GroupBy' or 'OrderBy' in what sequence do the records occur Blog bot DAX Blogs 0 20.04.2010 20:05
dynamicsaxtraining: Create purchase order Blog bot DAX Blogs 0 14.12.2009 14:05
dynamicsaxtraining: Setup initial data (Vendor, Warehouse, Equipment) Blog bot DAX Blogs 0 07.12.2009 19:05
Fred Shen: Always use recId to know if a select statement returns a record Blog bot DAX Blogs 0 28.10.2006 16:40

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

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

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