Correct way to use ListValueCount - coldfusion

I need to count total of ? in a given string. Here is my code:
<cfscript>
myString="UPDATE personnel SET personnel_id = ?, personnel_name = ?, personnel_nric = ?, personnel_staff_num = ?, personnel_designation = ?, personnel_department = ?, personnel_appointed_start_date = ?, personnel_appointed_end_date = ?, personnel_inspection_date = ?, personnel_org_id = ?, lt_dispose_personnel_type_id = ? WHERE id = 49;"
writeOutput("The count of ? is: " & ListValueCount(myString,"?",","))
</cfscript>
but here is my output : The count of ? is: 0. My expected output is 11. What is the correct way to use ListValueCount ? Thanks in advance.
CFfiddle : https://cffiddle.org/app/file?filepath=0dee010d-6bde-4ac9-939b-9867b53f128c/da1fade3-c26b-4703-a0b8-0037eddf6345/ecea7294-fba5-464e-ab2f-b919dd94f650.cfm

The issue is that ListValueCount() counts instances of a specified value in a list (see listValueCount at cfdocs ).
Because your delimiter is "," the list will break down into the following list item values (see here the trimmed values):
1. "UPDATE personnel SET personnel_id = ?"
2. "personnel_name = ?"
3. "personnel_nric = ?"
4. "personnel_staff_num = ?"
5. "personnel_designation = ?"
6. "personnel_department = ?"
7. "personnel_appointed_start_date = ?"
8. "personnel_appointed_end_date = ?"
9. "personnel_inspection_date = ?"
10. "personnel_org_id = ?"
11. "lt_dispose_personnel_type_id = ? WHERE id = 49;"
Because you are looking for the specific item value "?", no item can be found: Each of the string values above consist of more than one question mark!
Solution 1: Use a regular expression search, e.g.,
<cfscript>
myString="UPDATE personnel SET personnel_id = ? , personnel_name = ? , personnel_nric = ?, personnel_staff_num = ?, personnel_designation = ?, personnel_department = ?, personnel_appointed_start_date = ?, personnel_appointed_end_date = ?, personnel_inspection_date = ?, personnel_org_id = ?, lt_dispose_personnel_type_id = ? WHERE id = 49;"
writeOutput("The count of ? is: " & reFind("\?.+?,?", myString,1,true,"ALL").len())
</cfscript>
Solution 2: If you are using a more modern cfml engine, another possibility is to loop your list with a listReduce() member function like so:
<cfscript>
myString="UPDATE personnel SET personnel_id = ?, personnel_name = ?, personnel_nric = ?, personnel_staff_num = ?, personnel_designation = ?, personnel_department = ?, personnel_appointed_start_date = ?, personnel_appointed_end_date = ?, personnel_inspection_date = ?, personnel_org_id = ?, lt_dispose_personnel_type_id = ? WHERE id = 49;"
writeOutput("The count of ? is: " & myString.listReduce(
( acc, element ) => {
if( findNoCase( "?", element ) ){
return acc+1;
}else{
return acc;
}
}
, 0, ","
));</cfscript>
Solution 3 would be the classic way using cfloop and loop through each item and do findNoCase similar to the listReduce function above.
Side note: I suppose you are doing some kind of dynamic SQL query or debugging. Please be carefull creating those, especially when creating dynamic SQL queries. The regex solution 1 may have side effects according to the content of the list you are creating. You need to test it carefully!

Why ListValueCount is not the right tool for what you are trying to implement, is already well explained by #andreasRu.
There is one more alternative(in comments) to the answers provided by #andreasRu, which the following. I feel this is the simplest solution.
myString="UPDATE personnel SET personnel_id = ?, personnel_name = ?, personnel_nric = ?, personnel_staff_num = ?, personnel_designation = ?, personnel_department = ?, personnel_appointed_start_date = ?, personnel_appointed_end_date = ?, personnel_inspection_date = ?, personnel_org_id = ?, lt_dispose_personnel_type_id = ? WHERE id = 49;"
writeOutput("The count of ? is: " & Len(myString) - Len(Replace(myString, '?', '', 'all')))
We are simply checking the length difference between the initial string and the string after all ? are stripped from it.

Related

Power Query conditional sumif

I need to add a column that Sums the value column of all columns that have a common id. However, any id = null is not summed, but equal to the value column.
The above example should result in:
TopPaymendId JournalLineNetAmount TopAmount
fcbcd407-ca26-4ea0-839a-c39767d05403 -3623.98 -7061.23
fcbcd407-ca26-4ea0-839a-c39767d05403 -3437.25 -7061.23
ce77faac-1638-40e9-ad62-be1813ce9031 -88.68 -88.68
531d9bde-3f52-47f3-a9cf-6f3566733af2 -152.23 -152.23
8266dfef-dd14-4654-a6d2-091729defde7 229.42 229.42
f8b97a47-15ef-427d-95e0-ce23cc8efb1f -777 -777
null -3.01 -3.01
null -2.94 -2.94
null 3312.5 3312.5
This code should work:
let
Source = Excel.CurrentWorkbook(){[Name="Data"]}[Content],
group = Table.Group(Source, {"TopPaymendId"}, {"TopAmount", each List.Sum([JournalLineNetAmount])}),
join = Table.Join(Source,{"TopPaymendId"},group,{"TopPaymendId"}),
replace = Table.ReplaceValue(join,each [TopAmount],each if [TopPaymendId] = null
then [JournalLineNetAmount] else [TopAmount],Replacer.ReplaceValue,{"TopAmount"})
in
replace

My program reads 0 from the database even though there is a 1

I don't understand whats wrong with the code, I have read a lot of times but I can't find the error
pstmt = con->prepareStatement("SELECT (?) FROM votos WHERE id = (?)");
pstmt->setString(1, eleccion);
pstmt->setInt(2, p->getId());
res = pstmt->executeQuery();
while(res->next())
{
p->setVoto(res->getInt(1));
}
When the eleccion and id variables are Provincial and 1 respectively the getInt(1) function should return 1, but it returns 0.
The command (in the mysql command line):
SELECT Provincial from Votos WHERE id=1
Returns a table with one row and one column with the value 1
Side notes:
Spelling was checked
The getId() function works correctly
The compiler doesn't give any error
You can't use a placeholder in a prepared query for a column name. It's returning the value of the string eleccion, not using it as the name of a column in the table. You need to do string concatenation to substitute the column name.
std::string sql = std::string("SELECT `") + eleccion + "` FROM votos WHERE id = ?";
pstmt = con->prepareStatement(sql.c_str());
pstmt->setInt(1, p->getId());
res = pstmt->executeQuery();
while(res->next())
{
p->setVoto(res->getInt(1));
}
If the value of eleccion is coming from the user or some other untrusted source, make sure you validate it before concatenating, to prevent SQL injection.

SQL Insert From PowerQuery

I need to convert a query on excel to a Insert on SQL, I wont to create a function that will work on any query, and Invoke it, so he need to be quite reusable.
let
SQL = (TableX as table) => let
// Get Columns Name abd use on the columns INSERT
SOURCE = TableX,
Names = Table.ColumnNames(SOURCE),
ListN = Table.FromList(Names),
TransposeN = Table.Transpose(ListN),
CombineN = Table.CombineColumns(TransposeN,Table.ColumnNames(TransposeN),Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"M"),
ColunmsAsText = List.Single(CombineN[M]),
// ColumnsasText is all the Columns Name
// This part I cant do I need to format all columns acording to the type and Combine They
COLUNMS = (ListN as text) => let
TYPE = some.function.to.get.type(SOURCE[ListN]),
if TYPE = date then FIELDS = FIELDS & "'" & Date.ToText([ListN], "yyyy-MM-dd") & "'," else
if TYPE = text then FIELDS = FIELDS & "'" & [ListN] & "'," else
if TYPE = number then FIELDS = FIELDS & [ListN] & "," else FIELDS = FIELDS & "#error,"
in
FIELDS
INSERT = "INSERT INTO " & "TABLENAME" & " (" & ColunmsAsText & ") VALUES (" & FIELDS & ");",
NEWCOLUMNADD = Table.AddColumn(SOURCE, "SQL", each INSERT)
in
NEWCOLUMNADD
in
SQL
The problem is the FIELDS variable where, I need to compose a string of all columns, and the function "some.function.to.get.type", and the output 'll be something like this, for each row:
INSERT INTO (Column_name1, Column_name2, Column_name3) value (15, '2017-05-20', 'Text hear');
Tanks for the help.
You want Value.Type
Value.Type("abc") = type text

Bind specific parameter (one) in JPQL

In database I have partitioning table by column 'status' for better performance. My database administrator ask me about put in query value for that column directly in sql (not bind by parameter).
I can change binding by set hint QueryHints.BIND_PARAMETERS on false, but then all parameters are inside sql.
Can I set not bind only on 'status' parameter ?
Example result when BIND_PARAMETERS = true
SELECT t0.* FROM S_JOBS_ORG_UNIT_CFG t0
WHERE ((((t0.ORG_ID = ?) AND (t0.SCHEDULER_NEXT_ACTIVATION < SYSDATE)) AND (t0.ACTIVE = ?))
AND NOT EXISTS (SELECT ? FROM S_JOBS t1 WHERE (((t1.ORDER_ID = t0.ORDER_ID) AND (t1.ORG_ID = t0.ORG_ID)) AND NOT ((t1.STATUS = ?)))) )
bind => [472100, Y, 1, E]
and result when BIND_PARAMETERS = false
SELECT t0.* FROM S_JOBS_ORG_UNIT_CFG t0
WHERE ((((t0.ORG_ID = 472100) AND (t0.SCHEDULER_NEXT_ACTIVATION < SYSDATE)) AND (t0.ACTIVE = Y))
AND NOT EXISTS (SELECT 1 FROM S_JOBS t1 WHERE (((t1.ORDER_ID = t0.ORDER_ID) AND (t1.ORG_ID = t0.ORG_ID)) AND NOT ((t1.STATUS = E)))) )
Code:
Query jobOrgUnitCfgQuery = entityManager.createQuery(
"SELECT c FROM JobOrgUnitCfg c WHERE c.orgId = :orgId and c.schedulerNextActivation < current_timestamp and c.active = :active and " +
" not exists (SELECT j FROM Job j WHERE j.orderId = c.orderId and j.orgId = c.orgId and j.status <> 'E')");
jobOrgUnitCfgQuery.setParameter("orgId", orgId);
jobOrgUnitCfgQuery.setParameter("active", Boolean.TRUE);
return jobOrgUnitCfgQuery.getResultList();
I think your best bet is just to programmatically build your query like you're doing with a hard coded status and escape the other paramaters manually to avoid SQL Injection.

Conversion of PerfRawData Values into Performatted data -WMI

I need to convert PagesPersec value from Win32_PerfRawData_PerfOS_Memory to PerfFormatted Data value .How to convert PerfRaw data values from WMI Perfomance counters to PerfFormatted Data values .Is there Standard Formula available recommended by Windows.
The formula you need depends on the CounterType ... see
http://msdn.microsoft.com/en-us/library/aa392761(v=VS.85).aspx
to get started, have a look at http://msdn.microsoft.com/en-us/library/aa394597.aspx
It is too long to answer here. There is a very good article with samples http://msdn.microsoft.com/en-us/library/ms974615.aspx
In a brief: it depends on the counter type. For some counters it can me just read (disk free space) and come require calculation based on two requests one a bit later than another, for example:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_PerfRawData_PerfOS_Processor Where Name = '0'")
For Each objItem in colItems
CounterValue1 = objItem.InterruptsPerSec
TimeValue1 = objItem.TimeStamp_PerfTime
TimeBase = objItem.Frequency_PerfTime
Next
For i = 1 to 5
Wscript.Sleep(1000)
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_PerfRawData_PerfOS_Processor Where Name = '0'")
For Each objItem in colItems
CounterValue2 = objItem.InterruptsPerSec
TimeValue2 = objItem.TimeStamp_PerfTime
If TimeValue2 - TimeValue1 = 0 Then
Wscript.Echo "Interrupts Per Second = 0"
Else
intInterrupts = (CounterValue2 - CounterValue1) / _
( (TimeValue2 - TimeValue1) / TimeBase)
Wscript.Echo "Interrupts Per Second = " & Int(intInterrupts)
End if
CounterValue1 = CounterValue2
TimeValue1 = TimeValue2
Next
Next