TSQL / SSRS : Using LIKE with multi-valued parameters - tsql

I am trying to determine a solution to filter records using LIKE with a multi-valued parameter. In a simplistic example a user wants to return a set of 5-digit Object codes by entering the following in a parameter window in a SSRS report:
#parm_Object
1,24,333,34567
This ideally would return Object codes satisfying the following criteria:
1 : All Object codes starting with '1'
24: All Object codes starting with '24'
333: Similar
34567: Object code '34567'
I guess a starting point for me would be to determine whether this could be handled in the actual query, or should I do it on the SSRS side.

general good practice is to get rid of the data you don't need ASAP. so that would be in the query.
a SSRS multivalued parameter will show up as a comma separated list in the query.
the first step is to get from this comma separated list to a table (or table function), then you can join this table and apply like operators
for example
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS a
INNER JOIN dbo.split1('test,fafa,tata') b
ON 1=1
WHERE a.COLUMN_NAME like b.Value + '%'
will return rows having column names starting with test, fafa or tata. the dbo.split1 function you have to write your own or get one from the internet. the link suggested by Tab Alleman for example.

Related

SSRS multi value parameter - can't get it to work

First off this is my first attempt at a multi select. I've done a lot of searching but I can't find the answer that works for me.
I have a postgresql query which has bg.revision_key in (_revision_key) which holds the parameter. A side note, we've named all our parameters in the queries with the underscore and they all work, they are single select in SSRS.
In my SSRS report I have a parameter called Revision Key Segment which is the multi select parameter. I've ticked Allow multi value and in Available Values I have value field pointing to revision_key in the dataset.
In my dataset parameter options I have Parameter Value [#revision_key]
In my shared dataset I also have my parameter set to Allow multi value.
For some reason I can't seem to get the multi select to work so I must be missing something somewhere but I've ran out of ideas.
Unlike with SQL Server, when you connect to a database using an ODBC connection, the parameter support is different. You cannot use named parameters and instead have to use the ? syntax.
In order to accommodate multiple values you can concatenate them into a single string and use a like statement to search them. However, this is inefficient. Another approach is to use a function to split the values into an in-line table.
In PostgreSQL you can use an expression like this:
inner join (select CAST(regexp_split_to_table(?, ',') AS int) as filter) as my on my.filter = key_column
Then in the dataset properties, under the parameters tab, use an expression like this to concatenate the values:
=Join(Parameters!Keys.Value, ",")
In other words, the report is concatenating the values into a comma-separated list. The database is splitting them into a table of integers then inner joining on the values.

Querying on multiple LINKMAP items with OrientDB SQL

I have a class that contains a LINKMAP field called links. This class is used recursively to create arbitrary hierarchical groupings (something like the time-series example, but not with the fixed year/month/day structure).
A query like this:
select expand(links['2017'].links['07'].links['15'].links['10'].links) from data where key='AAA'
Returns the actual records contained in the last layer of "links". This works exactly as expected.
But a query like this (note the 10,11 in the second to last layer of "links"):
select expand(links['2017'].links['07'].links['15'].links['10','11'].links) from data where key='AAA'
Returns two rows of the last layer of "links" instead:
{"1000":"#23:0","1001":"#24:0","1002":"#23:1"}
{"1003":"#24:1","1004":"#23:2"}
Using unionAll or intersect (with or without UNWIND) results in this single record:
[{"1000":"#23:0","1001":"#24:0","1002":"#23:1"},{"1003":"#24:1","1004":"#23:2"}]
But nothing I've tried (including various attempts at "compound" SELECTs) will get the expand to work as it does with the original example (i.e. return the actual records represented in the last LINKMAP).
Is there a SQL syntax that will achieve this?
Note: Even this (slightly modified) example from the ODB docs does not result in a list of linked records:
select expand(records) from
(select unionAll(years['2017'].links['07'].links['15'].links['10'].links, years['2017'].links['07'].links['15'].links['11'].links) as records from data where key='AAA')
Ref: https://orientdb.com/docs/2.2/Time-series-use-case.html
I'm not sure of what you want to achieve, but I think it's worth trying with values():
select expand(links['2017'].links['07'].links['15'].links['10','11'].links.values()) from data where key='AAA'

IBM DB2 SQLException with "DB2 SQL Error: SQLCODE=-420, SQLSTATE=22018, SQLERRMC=DECFLOAT, DRIVER=3.66.46"

I am working on a Jasper report using iReport 5.6 and IBM DB2 as data source. I am passing a list of strings as a parameter to the report and that is where the problem rises. The query is below;
SELECT customers.mobile_number,
COALESCE(Count(DISTINCT transaction_entries.transaction_id), 0) AS
number_of_transactions,
COALESCE(Sum(Abs(transaction_entries.amount)) / 100, 0) AS
volume_of_transactions
FROM transaction_entries
JOIN customers
ON customers.id = transaction_entries.customer_id
WHERE transaction_entries.transaction_type = 'Seasonal'
AND transaction_entries.notification_text <> 'Notification'
AND customers.mobile_number IN ( $p ! {listOfMobileNumbers} )
GROUP BY customers.mobile_number
When I try to generate the report I get the error Caused by: com.ibm.db2.jcc.am.SqlDataException: DB2 SQL Error: SQLCODE=-420, SQLSTATE=22018, SQLERRMC=DECFLOAT, DRIVER=3.66.46.
Any idea why ? and the possible solution ?
I would first verify that by commenting-out the last predicate of the WHERE clause avoids the error; i.e. redact the failing statement such that the IN predicate referencing the Jasper variable as input is no longer part of the query.
Then, determine what defines that variable replacement, from the output of the following query:
select '$p ! {listOfMobileNumbers}' from sysibm.sysdummy1
If the effect of the above query, used to reveal the data in that list, presents something like '1234,567,890', then I would suggest modifying the data that defines that list to reflect either of '1234','567','890' or 1234, 567, 890 instead.
FWiW: IMO the actual DDL [for column(s) or the TABLE] is much clearer to a reader than suggesting merely that:
The mobile_number field is returned from the database as a String and not a DECIMAL

SSRS: Call a dataset from a textbox with a parameter

I have a dataset that is a query which has a where clause like this 'where field1 like #parameter1' parameter1 is a string defined as a parameter in the dataset1. I have various text boxes that calls the dataset with expressions like =First(Fields!field_xx, "Dataset1"). For each textbox I like to specify a different value for #parameter1 when it calls the "dataset1". How can I modify the expression in each textbox as to call the "dataset1" from each of them with a hardcoded value for #parameter1
the query:
SELECT TOP (1) job.job_id, job.originating_server, job.name, job.enabled, job.description, job.start_step_id, job.category_id, job.owner_sid, job.notify_level_eventlog,
job.notify_level_email, job.notify_level_netsend, job.notify_level_page, job.notify_email_operator_id, job.notify_netsend_operator_id, job.notify_page_operator_id,
job.delete_level, job.date_created, job.date_modified, job.version_number, job.originating_server_id, job.master_server, activity.session_id, activity.job_id AS Expr1,
activity.run_requested_date, activity.run_requested_source, activity.queued_date, activity.start_execution_date, activity.last_executed_step_id,
activity.last_executed_step_date, activity.stop_execution_date, activity.job_history_id, activity.next_scheduled_run_date, steps.step_name
FROM sysjobs_view AS job INNER JOIN
sysjobactivity AS activity ON job.job_id = activity.job_id INNER JOIN
sysjobsteps AS steps ON activity.last_executed_step_id = steps.step_id AND activity.job_id = steps.job_id
WHERE (job.name LIKE 'Actual Job Name')
ORDER BY activity.start_execution_date DESC
It is not possible to call a dataset with different parameters in the same report execution. Every execution and rendering of the report fetches each dataset only once.
This means that you have to construct your dataset in a way so that it returns all the data you need, to populate each of your textboxes.
Depending on your data model, you may want to add more columns to your dataset, or return the data in multiple rows. If you have multiple rows, then you can use the Lookup function in an expression, to filter out the row in each individual textbox.
Perhaps if you elaborated a little more on what your report should look like, and what the structure of the data you are fetching is, it would be possible to give a better answer to how to solve your problem with a single dataset.

How do I prevent sql injection if I want to build a query in parts within the fatfree framework?

I am using the fatfree framework, and on the front-end I am using jQuery datatables plugin with server-side processing. And thus, my server-side controller may or may not receive a variable number of information, for example a variable number of columns to sort on, a variable number of filtering options and so forth. So if I don't receive any request for sorting, I don't need to have a ORDER BY portion in my query. So I want to generate the query string in parts as per certain conditions and join it at the end to get the final query for execution. But if I do it this way, I won't have any data sanitization which is really bad.
Is there a way I can use the frameworks internal sanitization methods to build the query string in parts? Also is there a better/safer way to do this than how I am approaching it?
Just use parameterized queries. They are here to prevent SQL injection.
Two possible syntaxes are allowed:
with question mark placeholders:
$db->exec('SELECT * FROM mytable WHERE username=? AND category=?',
array(1=>'John',2=>34));
with named placeholders:
$db->exec('SELECT * FROM mytable WHERE username=:name AND category=:cat',
array(':name'=>'John',':cat'=>34));
EDIT:
The parameters are here to filter the field values, not the column names, so to answer more specifically to your question:
you must pass filtering values through parameters to avoid SQL injection
you can check if column names are valid by testing them against an array
Here's a quick example:
$columns=array('category','age','weight');//columns available for filtering/sorting
$sql='SELECT * FROM mytable';
$params=array();
//filtering
$ctr=0;
if (isset($_GET['filter']) && is_array($_GET['filter'])
foreach($_GET['filter'] as $col=>$val)
if (in_array($col,$columns,TRUE)) {//test for column name validity
$sql.=($ctr?' AND ':' WHERE ')."$col=?";
$params[$ctr+1]=$val;
$ctr++;
}
//sorting
$ctr=0;
if (isset($_GET['sort']) && is_array($_GET['sort'])
foreach($_GET['sort'] as $col=>$asc)
if (in_array($col,$columns,TRUE)) {//test for column name validity
$sql.=($ctr?',':' ORDER BY ')."$col ".($asc?'ASC':'DESC');
$ctr++;
}
//execution
$db->exec($sql,$params);
NB: if column names contain weird characters or spaces, they must be quoted: $db->quote($col)