Want to create user-accessible form in Axapta that uses SQL with a substring function - sql

I have some sqlserver sql that due to data can't be modified, which I currently run from Sqlserver. It uses a substring function. I want to stop running it from Sqlserver and create a user-accessible form in which the user enters a date and the script goes off and does it's thing and returns row data to the user.
Not overly familar with X++. I've looked at reports, querys, jobs, statement classes, not sure what's the correct path.
Below is the sql code.
'
select a.description,b.itemid, c.phantom,a.createddatetime,a.createdby
from sysdatabaselog A
inner join
bomversion B
on substring(a.description,1,11) = b.bomid
inner join
inventtable C
on b.itemid = c.itemid
where (table_ = 18 and logtype=1)
and a.CREATEDDATETIME > '2018-03-01' <-------- this would be user-supplied on the form
and c.phantom=1
'

What you're trying to accomplish is actually pretty high-level in AX and requires a several different dev techniques to accomplish it. I'm not going to do the entire thing for you, but I'll get you started and tell you what you need to do. These screenshots are from AX2012.
To accomplish the SUBSTRING() you need an AX View + String computed column.
For your view, you'll want an AX Query object to contain your joins OR you can just do a simple view on the BOMVersion table and then work against that.
Here's an example View and String computed column and the method for the computed column. I just used SalesTable and SalesId as the sample.
public static server str compSubStrSalesName()
{
str result;
result = strFmt("SUBSTRING(%1, 1, 5)",
SysComputedColumn::returnField(identifierStr(SubStringExample), // The name of your view
identifierStr(SalesTable_1), // The name of your view's datasource
identifierStr(SalesId) // The name of the field
)
);
return result;
}

Related

How can use executeQueryWithParameters with SQLBuilderSelectExpression to join an x++/sql statement in Microsoft Dynamics?

In Dynamics 365 for Finance and Operations, they describe a method of creating SQL statements "as objects, as opposed to text", but this is somewhat of a lie. They use the objects to create the text which then populates str sqlStatement = selectExpr.getExpression(null);
This sqlStatement would then feed the obsolete statement.executeQuery(sqlStatement);.
I can make the warning go away by using executeQueryWithParameters() with an empty map (SqlParams::create()) as the second parameter, but this seems to be "cheating".
Is there a way I can/should refactor the following to populate the map correctly?
SQLBuilderSelectExpression selectExpression = SQLBuilderSelectExpression::construct();
selectExpression.parmUseJoin(true);
SQLBuilderTableEntry vendTable = selectExpression.addTableId(tableNum(VendTable));
SQLBuilderTableEntry dirPartyTable = vendTable.addJoinTableId(tableNum(DirPartyTable));
SQLBuilderFieldEntry accountNum = vendTable.addFieldId(fieldNum(VendTable, AccountNum));
SQLBuilderFieldEntry name = dirPartyTable.addFieldId(fieldNum(DirPartyTable, Name));
SQLBuilderFieldEntry dataAreaId = vendTable.addFieldId(fieldNum(VendTable, dataAreaId));
SQLBuilderFieldEntry blocked = vendTable.addFieldId(fieldNum(VendTable, Blocked));
vendTable.addRange(dataAreaId, curext());
vendTable.addRange(blocked, CustVendorBlocked::No);
selectExpression.addSelectFieldEntry(SQLBuilderSelectFieldEntry::newExpression(accountNum, 'AccountNum'));
selectExpression.addSelectFieldEntry(SQLBuilderSelectFieldEntry::newExpression(name, 'Name'));
str sqlStatement = selectExpression.getExpression(null);
// FIXME:
ResultSet resultSet = statement.executeQueryWithParameters(sqlStatement, SqlParams::create());
Below is how you would write your code as a standard X++ query. However, I must note that what you're doing may not be the best approach.
DirPartyTable is a special table in AX as it supports inheritance, so you should make sure you fully understand the framework. See:
https://learn.microsoft.com/en-us/dynamicsax-2012/appuser-itpro/implementing-the-global-address-book-framework-white-paper
https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/fin-ops/organization-administration/overview-global-address-book
Code:
VendTable vendTable;
DirPartyTable dirPartyTable;
while select AccountNum from vendTable
where vendTable.Blocked == CustVendorBlocked::No
// DataAreaId along with Partition, are automatically included in the query context depending
// on the company context you're executing the code from
// && vendTable.dataAreaId == curext()
join Name from dirPartyTable
where dirPartyTable.RecId == vendTable.Party
{
info(strFmt("Account: %1; Name: %2", vendTable.AccountNum, dirPartyTable.Name));
}
Regarding an AOT query, look in the AOT at \Queries\VendTableListPage and expand the data sources and learn from it.
Regardless of what OP is trying to do with the query, the answer to the question of "how do I correctly replace executeQuery with executeQueryWithParameters" can be found in the following article.
https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/query-with-parameters
The new *WithParameters APIs were introduced as a way to mitigate sql injection attacks which may occur when building up sql strings manually with un-sanitized sql parameters as input.
Snippet of the code example from above doc shows how to correctly populate the map to match the sql statement:
str sql = #"
UPDATE Wages
SET Wages.Wage = Wages.Wage * #percent
WHERE Wages.Level = #Level";
Map paramMap = SqlParams::create();
paramMap.add('percent', 1.1); // 10 percent increase
paramMap.add('Level', 'Manager'); // Management increase
int cnt = statement.executeUpdateWithParameters(sql, paramMap);

DbContext.DbSet.FromSql() not accepting parameters

I have a database with two tables, and wrote a relatively simple select statement that combines the data and returns me the fields I want. In my SQL developer software it executes just fine.
Now to execute it in my C# .NET Core application, I created a "fake" DbSet in my DbContext that doesn't have a proper table on the database. The Type of the DbSet is a Model that represents the resulting data structure of the select statement. I use the DbSet field to access the method FromSql() and execute the select like so:
List<ProjectSearchModel> results = _ejContext.ProjectSearch.FromSql(
#"SELECT combined.Caption, combined.Number FROM
(SELECT p.Caption, p.Number, CreateDate FROM dbo.Project AS p
UNION
SELECT j.Caption, j.Number, CreateDate FROM dbo.Job AS j) AS combined
WHERE combined.Caption LIKE '{0}%' OR combined.Number LIKE '{0}%'
ORDER BY combined.CreateDate DESC
OFFSET 0 ROWS
FETCH FIRST 30 ROWS ONLY", term)
.ToList();
The SQL does properly return data, I've tested that. But the result variable holds 0 entries after executing. In the documentation for FromSql() I found that with MS SQL Servers you have to use OFFSET 0 when using ORDER BY so that's what I did.
I have no idea what I'm doing wrong.
You need to use DbQuery<T> instead:
public DbQuery<Project> ProjectSearch { get; set; }
Then, you can issue arbitrary queries using FromSql on that. With DbSet, the query must be composable, which means it can only be a standard select, it must correspond to a real table, and must include all properties on the entity - none of which apply to the query you're trying to perform.
As #ChrisPratt said, one of my mistakes was using the DbSet class instead of the DbQuery class. But also, what drove me crazy is that my parameters didn't work. My mistake was putting them inside a string, which results in them not being recognized as parameters. So my SQL string should be
...
WHERE combined.Caption LIKE {0} + '%' OR combined.Number LIKE {0} + '%'
...
instead of
...
WHERE combined.Caption LIKE '{0}%' OR combined.Number LIKE '{0}%'
...

Syntax error on WITH clause

I am working on a web app and there are some long winded stored procedures and just trying to figure something out, I have extracted this part of the stored proc, but cant get it to work. The guy who did this is creating alias after alias.. and I just want to get a section to work it out. Its complaining about the ending but all the curly brackets seem to match. Thanks in advance..
FInputs is another stored procedure.. the whole thing is referred to as BASE.. the result of this was being put in a temp table where its all referred to as U. I am trying to break it down into separate sections.
;WITH Base AS
(
SELECT
*
FROM F_Inputs(1,1,100021)
),
U AS
(
SELECT
ISNULL(q.CoverPK,r.CoverPK) AS CoverPK,
OneLine,
InputPK,
ISNULL(q.InputName,r.InputName) AS InputName,
InputOrdinal,
InputType,
ParentPK,
InputTriggerFK,
ISNULL(q.InputString,r.InputString) AS InputString,
PageNo,
r.RatePK,
RateName,
Rate,
Threshold,
ISNULL(q.Excess,r.Excess) AS Excess,
RateLabel,
RateTip,
Refer,
DivBy,
RateOrdinal,
RateBW,
ngRequired,
ISNULL(q.RateValue,r.RateValue) AS RateValue,
ngClass,
ngPattern,
UnitType,
TableChildren,
TableFirstColumn,
parentRatePK,
listRatePK,
NewParentBW,
NewChildBW,
ISNULL(q.SumInsured,0) AS SumInsured,
ISNULL(q.NoItems,0) AS NoItems,
DisplayBW,
ReturnBW,
StringBW,
r.lblSumInsured,
lblNumber,
SubRateHeading,
TrigSubHeadings,
ISNULL(q.RateTypeFK,r.RateTypeFK) AS RateTypeFK,
0 AS ListNo,
0 AS ListOrdinal,
InputSelectedPK,
InputVis,
CASE
WHEN ISNULL(NewChildBW,0) = 0
THEN 1
WHEN q.RatePK is NOT null
THEN 1
ELSE RateVis
END AS RateVis,
RateStatus,
DiscountFirstRate,
DiscountSubsequentRate,
CoverCalcFK,
TradeFilter,
ngDisabled,
RateGroup,
SectionNo
FROM BASE R
LEFT JOIN QuoteInputs Q
ON q.RatePK = r.RatePK
AND q.ListNo = 0
AND q.QuoteId = 100021 )
Well, I explained the issue in the comments section already. I'm doing it here again, so future readers find the answer more easily.
A WITH clause is part of a query. It creates a view on-the-fly, e.g.:
with toys as (select * from products where type = 'toys') select * from toys;
Without the query at the end, the statement is invalid (and would not make much sense anyhow; if one wanted a permanent view for later use, one would use CREATE VIEW instead).

Handle null values within SQL IN clause

I have following sql query in my hbm file. The SCHEMA, A and B are schema and two tables.
select
*
from SCHEMA.A os
inner join SCHEMA.B o
on o.ORGANIZATION_ID = os.ORGANIZATION_ID
where
case
when (:pass = 'N' and os.ORG_ID in (:orgIdList)) then 1
when (:pass = 'Y') then 1
end = 1
and (os.ORG_SYNONYM like :orgSynonym or :orgSynonym is null)
This is a pretty simple query. I had to use the case - when to handle the null value of "orgIdList" parameter(when null is passed to sql IN it gives error). Below is the relevant java code which sets the parameter.
if (_orgSynonym.getOrgIdList().isEmpty()) {
query.setString("orgIdList", "pass");
query.setString("pass", "Y");
} else {
query.setString("pass", "N");
query.setParameterList("orgIdList", _orgSynonym.getOrgIdList());
}
This works and give me the expected output. But I would like to know if there is a better way to handle this situation(orgIdList sometimes become null).
There must be at least one element in the comma separated list that defines the set of values for the IN expression.
In other words, regardless of Hibernate's ability to parse the query and to pass an IN(), regardless of the support of this syntax by particular databases (PosgreSQL doesn't according to the Jira issue), Best practice is use a dynamic query here if you want your code to be portable (and I usually prefer to use the Criteria API for dynamic queries).
If not need some other work around like what you have done.
or wrap the list from custom list et.

DISTINCT is not working

SQL query in Ms-Access
INSERT INTO tblTmpEventLog( TrackingNumber, PartNumber, PartNumberChgLvl,
EnteredBy, EventTypeSelected, EventDate )
SELECT DISTINCT tblRevRelLog_Detail.RevRelTrackingNumber,
tblRevRelLog_Detail.PartNumber, tblRevRelLog_Detail.ChangeLevel,
[Forms]![frmEventLog_Input]![EnteredBy] AS EnteredBy,
[Forms]![frmEventLog_Input]![EventTypeSelected] AS EventTypeSelected,
CDate([Forms]![frmEventLog_Input]![EventDate]) AS EventDate
FROM tblRevRelLog_Detail LEFT JOIN tblEventLog
ON (tblEventLog.PartNumber = tblRevRelLog_Detail.PartNumber)
AND (tblEventLog.PartNumberChgLvl = tblRevRelLog_Detail.ChangeLevel)
WHERE ((([tblRevRelLog_Detail]![RevRelTrackingNumber]) =
[Forms]![frmEventLog_Input]![TrackingNumber]))
AND ((tblEventLog.PartNumber) NOT IN
(SELECT tblEventLog.PartNumber FROM tblEventLog
WHERE tblEventLog.EventTypeSelected = 'pn REMOVED From Wrapper'
AND tblEventLog.TrackingNumber =
tblRevRelLog_Detail.RevRelTrackingNumber
AND tblEventLog.PartNumber = tblRevRelLog_Detail.PartNumber
AND tblEventLog.PartNumberChgLvl =
tblRevRelLog_Detail.ChangeLevel
));
DISTINCT keyword for EnteredBy, EventTypeSelected is not working..I mean, data for these columns is not displaying when I use DISTINCT keyword.
EVENTDATE is working fine, but I do not understand why is it not displaying for EneteredBy and EventTypeSelected columns.
Can anyone tell me how to handle this?
It may be that the query can't interpret properly from the form directly as the final data type. However in your date field, you are wrapping it in a function CDATE( ... ). So, the SQL engine knows the result type. I would suggest doing the same for the other fields. Ex: doing a CAST ( ...your form control... as DateTime ) as OtherColumn, etc... I THINK Access allows casting, but not positive. Otherwise, pre-pull the form value into a declared data type variable and use THAT variable in the query AS OtherColumn as you are doing.
Additionally to what #Jack mentioned, you can always go back to your account, look at your historical question, and click on whatever answers actually helped / solve your problems. Some questions never do get answers and that's ok, just give credit to those that DO help.
I have found in the past (I don't remember which old version of Access this was) that if you set the value of a form control in VBA, and then use that control in a query, the query will not see the value you set in VBA. If the user edits the control normally, the query sees the expected value. Perhaps that's what happened here.
To work around that, you can declare a VBA function that returns the desired value. For example, instead of this:
SELECT ..., Forms!MainForm!TextEntry AS TextEntry, ... FROM ...
use this:
SELECT ..., GetTextEntry() AS TextEntry, ... FROM ...
along with this:
Public Function TextEntry() As Variant
TextEntry = Forms!MainForm!TextEntry
End Function