Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto? Parameters and LIKE statement SQL

I am writing a searching function, and have thought up of this query using parameters to prevent, or at least limit, SQL injection attacks. However, when I run it through my program it does not return anything:

SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')

Can parameters be used like this? or are they only valid in an instance such as:

SELECT * FROM compliance_corner WHERE body LIKE '%<string>%' (where <string> is the search object).

EDIT: I am constructing this function with VB.NET, does that have impact on the syntax you guys have contributed?

Also, I ran this statement in SQL Server: SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE%max%')` and that returns results.

like image 593
Anders Avatar asked Oct 30 '08 18:10

Anders


People also ask

How do you use like in parameters?

Create a select query, and then open the query in Design view. In the Criteria row of the field you want to add a parameter to, type Like "*"&[, the text that you want to use as a prompt, and then ]&"*".

Can you combine like and in statements SQL?

Kevin is right, you cannot combine the in and like items as you've done it. Full text might help, but you'll still be building a string with multiple and statements for your CONTAINS (or other predicate) statement.

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.


1 Answers

Well, I'd go with:

 Dim cmd as New SqlCommand(  "SELECT * FROM compliance_corner"_   + " WHERE (body LIKE @query )"_    + " OR (title LIKE @query)")   cmd.Parameters.Add("@query", "%" +searchString +"%") 
like image 98
James Curran Avatar answered Oct 14 '22 03:10

James Curran