views:

62

answers:

4

I have a table Customer with 2 columns Name and Surname (sql Server 2008). User wants to search by Name-Surname - or just typing Jo Bloggs. Suppose a row is filled with

CustomerId        Name    Surname
1                 Jo      Bloggs

doing

select * from customer where Name like '%Jo%'             will find the records
select * from customer where Surname like '%Bloggs%'      will find the records

But How can I make it return records for if user types both Name and Surname eg Jo Bloggs?

+3  A: 
select * from customer where Name like '%Jo%' and Surname like '%Bloggs%'   
Pranay Rana
Should work ... even if the user doesn't type in a name or surname, like '%%' will match all ...
nonnb
will work - but it will always do a full table scan, since using `LIKE %Jo%` will not be able to be handled by an index.... performance will be ugly....
marc_s
A: 
select * from customer where Name like '%Jo%'             
union
select * from customer where Surname like '%Bloggs%'   
simple
This would give `or` I think the OP wants `and`
Martin Smith
+3  A: 

This should work whether user enters First Name, Surname or both.

SELECT *
FROM customer cus
WHERE ((cus.Name like @FirstName) OR (@FirstName IS NULL)) AND
      ((cus.Surname like @Surname) OR (@Surname IS NULL))

I used two variables because entering input values into an SQL string is strongly discouraged, as it exposes to SQL Injection (other than being slower).

Diego
Thanks everybody for your replies.More than one answer would work but I had to choose one.Thanks
+4  A: 

You could also create a computed column and search on that:

ALTER TABLE dbo.customer
   ADD FullName as Name + ' ' + Surname PERSISTED

Now you'd have an extra column FullName in your customer table, which is always up to date, and you can search for:

SELECT (list of fields) FROM dbo.customer 
  WHERE Fullname = 'Jo Bloggs'

and since it's a persisted, computed column, you can even put an index on it to make exact searches faster

marc_s