J'ai le code suivant:Utilisation de SqlParameter à la clause SQL LIKE ne fonctionne pas
const string Sql =
@"select distinct [name]
from tblCustomers
left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId
where (tblCustomer.Name LIKE '%@SEARCH%' OR tblCustomerInfo.Info LIKE '%@SEARCH%');";
using (var command = new SqlCommand(Sql, Connection))
{
command.Parameters.AddWithValue("@SEARCH", searchString);
...
}
Cela ne fonctionne pas, j'essayé ainsi:
const string Sql =
@"select distinct [name]
from tblCustomers
left outer join tblCustomerInfo on tblCustomers.Id = tblCustomerInfo.CustomerId
where (tblCustomer.Name LIKE @SEARCH OR tblCustomerInfo.Info LIKE @SEARCH);";
using (var command = new SqlCommand(Sql, Connection))
{
command.Parameters.AddWithValue("@SEARCH", "'%" + searchString + "%'");
...
}
mais cela ne fonctionne pas aussi bien . Qu'est-ce qui ne va pas? Aucune suggestion?
command.Parameters.AddWithValue (» @SEARCH ","% "+ searchString +"% "); Travaillé, les guillemets simples supplémentaires ont été le problème comme vous l'avez souligné – Ngm
Le faire de la deuxième manière me semble meilleur parce que la déclaration finale semblera en effet soignée. – Javid
Cela ne fonctionnera pas correctement lorsque searchString contient les caractères '%' '_' ou' [', en supposant que vous voulez réellement rechercher l'un de ces littéraux de charater. Pour une solution à 100%, vous devez placer ces caractères dans la chaîne searchString entre parenthèses '[]'. Le code C# 'Regex.Replace (searchString, @" ([% _ \ []) ", @" [$ 1] ")' fait l'affaire. –