Oshrib
Oshrib

Reputation: 1900

Find string in SQL column

I have the next code(found here at stack overflow):

 string [] arr = {"One","Two","Three"};
   var target = "One";
   var results = Array.FindAll(arr, s => s.Equals(target));

This code good for search string on array... i need to find string in sql column.

Let's say i have table ("Names"), and i want to find "Jhon".. how can i do that?

Upvotes: 1

Views: 1988

Answers (2)

Bob Vale
Bob Vale

Reputation: 18474

Well to avoid sql injection if target is user provided

string connectionString= ...
string target="jh";

using (var conn=new SqlConnection(connectionString)) {
conn.Open();
  using (var cmd=conn.CreateCommand()) {
    cmd.CommandText="select Name from Names where Name like '%'+@value+'%'";
    cmd.Parameters.AddWithValue("@value",target);

    using (var reader=cmd.ExecuteReader()) {
        while (reader.Read()) { 
            Console.WriteLine(reader[0]);
        }
    }

  }
}
  • Use like '%'+@value+'%' for contains
  • Use like @value+'%' for starts with
  • Use like '%'+@value for ends with

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460108

SELECT NAME
FROM NAMES
WHERE NAME='Jhon'

Is this what you're looking for?

If only a part of it needs to match:

...
WHERE NAME LIKE 'Jh%'

LIKE

Upvotes: 2

Related Questions