Adam Levitt
Adam Levitt

Reputation: 10476

C# SQL Server Query First/Last Name Columns where First Name Has Space

I have a table structure like so:

user_id | first_name | last_name
      1 | John       | Smith
      2 | Mary       | Jones
      3 | Sang He    | Lau

// here is a sample of the code I currently have to do a user search
public List<string> getResults(string autocompleteQuery) {
  string[] tokens = autocompleteQuery.Split(' ');

  // token[0] = first name parameter (@firstName)
  // token[1] = last name parameter  (@lastName)

  // code here executes the following query:
  // SELECT * FROM [user] WHERE first_name = @firstName AND last_name = @lastName
}

My issue here is that the following code that uses a space as a list delimiter combined with the query do not work when there is a space in the first name as shown in user_id = 3.

How can I elegantly upgrade either the code or query to handle this case? Thanks.

Upvotes: 1

Views: 360

Answers (1)

armen.shimoon
armen.shimoon

Reputation: 6401

SELECT * FROM [user]
WHERE 
  first_name + last_name LIKE '%' + token[0] + '%'
AND
  first_name + last_name LIKE '%' + token[1] + '%'
AND
  first_name + last_name LIKE '%' + token[2] + '%'
...

Upvotes: 1

Related Questions