문제

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!

도움이 되었습니까?

해결책

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%.

다른 팁

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%";

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top