1

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.

CloudPotato
  • 1,255
  • 1
  • 17
  • 32

2 Answers2

1

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.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • I'm not sure even if it seems to be a id (integer) list that it is recommend to use this kind of string replacement, I think prepared statement is always prefeered – Petter Friberg Aug 03 '16 at 22:00
1

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

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
  • 2
    SQL-injection isn't a problem for my project, because the DB is local and the data in it aren't interesting. But I agree that this can be a problem in other projects. `$X` is completly new for me. As far as I read about it, it seems to be very good solution. Thank you for your answer. – CloudPotato Aug 04 '16 at 07:04