Rudi Thiel
Rudi Thiel

Reputation: 2551

Can't get delphi SQL LIKE to work with %

I'm doing a school project and need to code a query to filter a dataset to certain variables. All my SQL works fine, except I can't get the LIKE statement to work with %-signs. I believe my syntax is wrong. Can anybody please tell me what I'm doing wrong. Thanks

The code:

qryMovie.SQL.Clear;
qryMovie.SQL.Add('SELECT * FROM Movies');
qryMovie.SQL.Add('WHERE Genre =  ' + QuotedStr(genre));
qryMovie.SQL.Add('AND Price BETWEEN ' + minPrice + ' AND ' + maxPrice);
qryMovie.SQL.Add('AND Title LIKE %' + title + '%');
qryMovie.Open;

Error produced:

'Syntax error in query expression 'Genre = 'Action/Adventure' AND Price BETWEEN 0 AND 200 AND Title LIKE %Star Wars%''

Upvotes: 1

Views: 4742

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175686

LIKE %Star Wars%

but you need

LIKE '%Star Wars%'

You need to quote % with ':

qryMovie.SQL.Add(' AND Title LIKE ''%' + title + '%''');

Anyway you should use binded parameters instead of concatenating SQL string. It is error-prone and could lead to SQL Injection attacks.

Upvotes: 8

Related Questions