1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| using (var connection = new System.Data.SqlClient.SqlConnection(
@"Data Source=(localdb)\v11.0;Initial Catalog=VetOffice;Integrated Security=True;"))
{
using (var command = new System.Data.SqlClient.SqlCommand())
{
command.Connection = connection;
command.CommandType = System.Data.CommandType.Text;
string textToSearch = "Cat Dar Joe";
//On construit la requête :
var builder = new System.Text.StringBuilder();
builder.Append("SELECT * FROM dbo.Patients WHERE 1=1 AND ");
var words = textToSearch.Split(' ');
int indexWord = 0;
foreach (var word in words)
{
if (indexWord != 0)
{
builder.Append(" OR ");
}
builder.AppendFormat(" Name LIKE @{0}{1} OR AnimalType_Species LIKE @{0}{1} ", "word", indexWord);
indexWord++;
}
command.CommandText = builder.ToString();
//On ajoute les paramètres :
for (int i = 0; i < indexWord; i++)
{
var parameterName = "word" + i;
command.Parameters.Add(parameterName, System.Data.SqlDbType.VarChar).Value = "%" + words[i] + "%";
}
try
{
connection.Open();
var dataReader = command.ExecuteReader();
while(dataReader.Read())
{
Console.WriteLine("{0} - {1} | {2}", dataReader[dataReader.GetOrdinal("Id")],
dataReader[dataReader.GetOrdinal("Name")], dataReader[dataReader.GetOrdinal("AnimalType_Species")]);
}
}
catch (Exception ex)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
}
finally
{
connection.Close();
Console.ResetColor();
}
} |