Using Parameters with the LIKE Statement in SQL
When developing a search function, it's crucial to minimize potential security risks like SQL injection attacks. One approach is using parameters in SQL queries. However, users may encounter issues when employing parameters with LIKE statements.
The following query demonstrates the intended parameter usage in the LIKE statement:
SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')
But, this query doesn't produce any results. This prompts the question: are parameters applicable in this context, or are they limited, as seen in this instance?
SELECT * FROM compliance_corner WHERE body LIKE '%<string>%'
Additionally, the user has provided an alternative query that returns results in SQL Server:
SELECT * FROM compliance_corner WHERE (body LIKE '%max%') OR (title LIKE%max%')
To effectively use parameters with the LIKE statement, it's recommended to reference the VB.NET code snippet below:
Dim cmd as New SqlCommand( _ "SELECT * FROM compliance_corner" _ + " WHERE (body LIKE @query )" _ + " OR (title LIKE @query)") cmd.Parameters.Add("@query", "%" +searchString +"%")
The above is the detailed content of Can SQL Parameters Be Used Effectively with LIKE Statements?. For more information, please follow other related articles on the PHP Chinese website!