Use String parameter for RegEx in query - sql-server

In my query (the database is a sql server) I use a RegEx for a select command like this:
SELECT * FROM test WHERE id LIKE '1[2,3]'
(This query is tested and returns the data I want)
I want to use a paramter for this RegEx. For that I definded the Paramter in iReport $P{id} as a string and the value is "1[2,3]".
In my query I use now this parameter like this:
SELECT * FROM test WHERE id LIKE $P{id}
As result I get a blank page. I think the problem is that the value of the parameter is defined with " ". But with ' ' I get a compiler error that the paramter isn't a string.
I hope someone can help me.

LIKE applies to text values, not to numeric values. Since id is numeric use something like this:
SELECT * FROM test WHERE id IN (12, 13)
with the parameter
SELECT * FROM test WHERE id IN ($P!{id_list})
and supply a comma separated list of ids for the parameter. The bang (!) makes sure that the parameter will be inserted as-is, without string delimiters.
Btw: LIKE (Transact-SQL) uses wildcards, not regex.
You can still use LIKE since there exists an implicit conversion from numeric types to text in T-SQL, but this will result in a (table or index) scan, where as the IN clause can take advantage of indexes.

The accepted answer works but it is using String replacement, read more about sql-injection, to understand why this is not good practice.
The correct way to execute this IN query in jasper report (using prepared statement) is:
SELECT * FROM test WHERE $X{IN, id, id_list}
For more information as the use of NOTIN, BETWEEN ecc. see JasperReports sample reference for query

Related

Is it possible to use an asterisk to display all the values of a single SSRS Parameter

Is it possible to use an asterisk to display all the values of a single SSRS Parameter? So basically you have a parameter for first name. You type * and all the first names display. Or you can use exact name.
Thanks
This is not really an SSRS issue but how you interpret the parameters in your dataset query.
You could easily achieve this if you dataest query looked something like this simple example.
SELECT * FROM myTable WHERE (FirstName = #pFirstName OR #pFirstName = '*')
This assumes your report parameter is called pFirstName

Multi value parameter not working in SSRS report

I have a SSRS report. there is a long SQL query on the main query, in the last SELECT I want to filter the results with WHERE expression, the filter should be with a multi value parameter.
I set the parameter in this way:
Create a new Dataset with a query.
Add a new parameter to the Parameters folder (with name NewParam).
Check the "Allow multiple values" checkbox.
Add the parameter to the "Main Query" and set the value with this expression:
=Join(Parameters!NewParam.Value,",")
At the end of the Main Query I filter the results:
select *
from #FinalStatusTbl
where Test_Number in (#NewParam)
order by Priority
The problem is:
On the report when I choose one value from the list I got expected results, but If I choose multi values the results are empty (not got an error.)
Do you have any idea why?
(When I try this: where Test_Number in ('Test 1', 'Test 2') it works well).
When you create a dataset with a sql query, multi valued parameters work with the in(#ParamName) without any changes.
Replace your =Join(Parameters!NewParam.Value,",") with just =Parameters!NewParam.Value and you should be fine.
That said, the reason you see people using that join expression is because sometimes your query will slow down considerably if your parameter has a lot of potential selections and you data is reasonably large. What is done here is to combine the join expression with a string splitting function in the dataset that converts the resulting Value1,Value2,Value3 string value in a table that can be used in the query via inner join.
This is also a requirement if passing multiple values as a parameter to a stored procedure, as you can't use the in(#ParamName) syntax.
You could try taking the parameter out of the where clause and use the parameter in the filters section of the dataset properties.
This will effectively shift the filtering from the SQL to SSRS.
What you need to do is split your string in the database. What is being passed to your query is 'Test 1, Test 2' as a complete string, NOT 'Test 1' and 'Test 2'. This is why a single value works, and multiple values do not.
Here is a really good link on how to split strings, in preparation for your scenario. The function I most often use is the CTE example, which returns a table of my split strings. Then I change my SQL query to use IN on the returned table.
In your example, you will want to write WHERE Test_Number IN (SELECT Item FROM dbo.ufn_SplitStrings(#NewParam) , where ufn_SplitString is the function you create from the link previously mentioned.
This is what I did and it works well to me. You can try it also.
=sum(if(Fields!Business_Code.Value = "PH"
and (Fields!Vendor_Code.Value = "5563"
and Fields!Vendor_Code.Value = "5564"
and Fields!Vendor_Code.Value = "5565"
and Fields!Vendor_Code.Value = "5551")
, Fields!TDY_Ordered_Value.Value , nothing ))

How to take apart information between hyphens in SQL Server

How would I take apart a column that contains string:
92873-987dsfkj80-2002-04-11
20392-208kj48384-2008-01-04
Data would look like this:
Filename Yes/No Key
Abidabo Yes 92873-987dsfkj80-2002-04-11
Bibiboo No 20392-208kj48384-2008-01-04
Want it to look like this:
Filename Yes/No Key
Abidabo Yes 92873-987dsfkj80-20020411
Bibiboo No 20392-208kj48384-20080104
whereby I would like to concat the dates in the end as 20020411 and 20080104. From the right side, the information is the same always. From the left it is not, otherwise I could have concatenated it. It is not an import issue.
As mentioned in the comments already, storing data like this is a bad idea. However, you can obtain the dates from those strings by using a RIGHT function like so:
SELECT RIGHT('20392-208kj48384-2008-01-04', 10)
Output:
2008-01-04
Depending on the SQLSERVER version you are using, you can use STRING_SPLIT which requieres COMPATIBILITY_LEVEL 130. You can also build your own User Defined Function to split the contents of a field and manipulate it as you need, you can find some useful examples of SPLIT functions in this thread:
Split function equivalent in T-SQL?
Assuming I'm correct and the date part is always on the right side of the string, you can simply use RIGHT and CAST to get the date (assuming, again, that the date is represented as yyyy-mm-dd):
SELECT CAST(RIGHT(YourColumn, 10) As Date)
FROM YourTable
However, Panagiotis is correct in his comment - You shouldn't store data like that. Each column in the database should hold only a single point of data, be it string, number or date.
Update following your comment and the updated question:
SELECT LEFT(YourColumn, LEN(YourColumn) - 10) + REPLACE(RIGHT(YourColumn, 10), '-', '')
FROM YourTable
will return the desired results.

MS SQL Excel Query wildcards

I'm trying to introduce LIKE clause with wildcards in SQL query that runs within Excel 2007, where parameters are taken from specific Excel cells:
SELECT Elen_SalesData_View.ItemCode, Elen_SalesData_View.ItemDescription,
Elen_SalesData_View.ItemValue, Elen_SalesData_View.Quantity,
Elen_SalesData_View.CustomerId, Elen_SalesData_View.CustomerName,
Elen_SalesData_View.SalesInvoiceId, Elen_SalesData_View.EffectiveDate,
Elen_SalesData_View.CountryId
FROM SM_Live.dbo.Elen_SalesData_View Elen_SalesData_View
WHERE (Elen_SalesData_View.EffectiveDate>=? And Elen_SalesData_View.EffectiveDate<=?)
AND (Elen_SalesData_View.CustomerName<>'PROMO')
AND (Elen_SalesData_View.ItemDescription LIKE '%'+?+'%')
The EffectiveDate parameters are running fine and bringing back data as expected. But since I introduced LIKE - query runs, but returns nothing.
It doesn't return any results without wildcards either (full description entered):
(Elen_SalesData_View.ItemDescription LIKE ?)
Is there a restriction to wildcards or LIKE clause? If so, is there a way around it? (I cannot use CONTAINS, as the ItemDescription field is not FULLTEXT)
Have a look at this reference which suggests that % itself is the wildcard character, although it may depend on the dialect of SQL you are using. If this is the case then your LIKE clause will simply be LIKE '%' but untested.
I've just got this to work by using the (Elen_SalesData_View.ItemDescription LIKE ?) syntax then having the cell that contains the parameter value include the wildcard characters. If you don't/can't include the wildcards then create a formula in a separate cell to wrap the value in % characters and use this cell for the parameter value.
Rhys
My query was correct. There was something wrong with the actual spreadsheet. After redoing all from scratch - it worked!
SELECT Elen_SalesData_View.ItemCode, Elen_SalesData_View.ItemDescription,
Elen_SalesData_View.ItemValue, Elen_SalesData_View.Quantity,
Elen_SalesData_View.CustomerId, Elen_SalesData_View.CustomerName,
Elen_SalesData_View.SalesInvoiceId, Elen_SalesData_View.EffectiveDate,
Elen_SalesData_View.CountryId
FROM SM_Live.dbo.Elen_SalesData_View Elen_SalesData_View
WHERE (Elen_SalesData_View.ItemDescription Like '%'+?+'%')
AND (Elen_SalesData_View.EffectiveDate>=?) AND (Elen_SalesData_View.EffectiveDate<=?)
AND (Elen_SalesData_View.CustomerName<>'PROMO')

Is there any C SQLite API for quoting/escaping the name of a table?

It's impossible to sqlite3_bind_text a table name because sqlite3_prepare_v2 fails to prepare a statement such as:
SELECT * FROM ? ;
I presume the table name is needed to parse the statement, so the quoting needs to have happened before sqlite3_prepare_v2.
Is there something like a sqlite3_quote_tablename? Maybe it already exists under a name I can't recognize, but I can't find anything in the functions list.
SQLite will escape identifiers for you with the %w format in the https://www.sqlite.org/printf.html family of functions.
your proposed sqlite3_quote_tablename function could sanitize the input to prevent sql injection attacks. To do this it could parse the input to make sure it is a string literal. http://sqlite.org/lang_expr.html#litvalue
If a table name has invalid characters in it you can enclose the table name in double quotes, like this.
sqlite> create table "test table" (id);
sqlite> insert into "test table" values (1);
sqlite> select * from "test table";
id
----------
1
Of course you should avoid using invalid characters whenever possible. It complicates development and is almost always unnecessary (IMO the only time it is necessary is when you inherit a project that is already done this way and it's too big to change).
When using SQLite prepared statements with parameters the parameter: "specifies a placeholder in the expression for a literal value that is filled in at runtime"
Before executing any SQL statement, SQLite "compiles" the SQL string into a series of opcodes that are executed by an internal Virtual Machine. The table names and column names upon which the SQL statement operates are a necessary part of the compilation process.
You can use parameters to bind "values" to prepared statements like this:
SELECT * FROM FOO WHERE name=?;
And then call sqlite3_bind_text() to bind the string gavinbeatty to the already compiled statement. However, this architecture means that you cannot use parameters like this:
SELECT * FROM ? WHERE name=?; // Can't bind table name as a parameter
SELECT * FROM FOO WHERE ?=10; // Can't bind column name as a parameter
If SQLite doesn't accept table names as parameters, I don't think there is a solution for your problem...
Take into account that:
Parameters that are not assigned values using sqlite3_bind() are treated as NULL.
so in the case of your query, the table name would be NULL which of course is invalid.
I was looking for something like this too and couldn't find it either. In my case, the expected table names were always among a fixed set of tables (so those were easy to validate). The field names on the other hand weren't so I ended up filtering the string, pretty much removing everything that was not a letter, number, or underscore (I knew my fields would fit this parameters). That did the trick.

Resources