How do you use the % modifier in a C# T-SQL query string?
-
25-06-2021 - |
Pregunta
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!
Solución
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%
.
Otros consejos
Please try:
like '%' + @userNameQuery + '%'
I'd recommend using it like this:
- Write your
query
asSELECT userName from tblUserInformation WHERE userName LIKE @userNameQuery
Make sure the
string
you bind as the parameter@userNameQuery
contains the necessary%
, i.e. declare it asvar userName = @"%name%";