Question

I am trying to write a basic query in C# that includes the use of the '%' modifier.

Here is my query:

SELECT userName 
FROM tblUserInformation 
WHERE userName LIKE %@userNameQuery%

When I run that I get a SQL exception saying

You have a syntax error near @userNameQuery.

I have encountered similar differences with SQL queries and C# sql query strings before but am unsure how to resolve this one. I have tried:

SELECT userID 
FROM tblUserInformation 
WHERE userName LIKE '%'@userNameQuery'%'

The one below does not throw an exception but returns no results. It should because I can run the same query against the database directly and it returns many results.

SELECT userName 
FROM tblUserInformation 
WHERE userName LIKE '%@userNameQuery%'

Am I doing this correctly?

Also, @userNameQuery is properly filled in with SqlParameter and is the correct data type etc. Having tried both above and the second one works (returning no results) I am sure that there is no syntax error in my query string (extra semicolon or missing ").

Thank you for your time!

Was it helpful?

Solution

You need to pass in the % in the value of the parameter, not have it in the query itself.

SELECT userName from tblUserInformation WHERE userName LIKE @userNameQuery

Where @userNameQuery would be like %my query%.

OTHER TIPS

Please try:

like '%' + @userNameQuery + '%'

I'd recommend using it like this:

  1. Write your query as SELECT userName from tblUserInformation WHERE userName LIKE @userNameQuery
  2. Make sure the string you bind as the parameter @userNameQuery contains the necessary %, i.e. declare it as

    var userName = @"%name%";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top