views:

645

answers:

2

I have SQL Server 2005 Report that takes a parameter in a query string that searches customer names. The problem is some customers like to put in a middle initial so when the user 'John Smith' this does not bring up 'John Q. Smith'.

Using only sql, how would I split a string into an array by whitespace then search records matching each string in the array to the result?

A: 

You can use a user-defined split function, like the one here and use that something like this:

SELECT *
FROM SomeTable t
WHERE NOT EXISTS (SELECT * FROM dbo.Split('John Smith', ' ') s WHERE t.NameColumn NOT LIKE '%' + s.Data + '%')

You'd need to see how this performs for you

Edit: Original version didn't do what you want - I glossed over the fact you want to match on ALL parts, whereas it would have returned all "John"s and all "Smith"s. Corrected to match on ALL parts now.

AdaTheDev
+2  A: 

Try this sql server 2005

DECLARE @UserName VARCHAR(MAX)

SELECT @UserName = 'John Smit'

DECLARE @User TABLE(
     UserName VARCHAR(MAX)
)

INSERT INTO @User (UserName) SELECT 'John Smit'
INSERT INTO @User (UserName) SELECT 'John Q. Smit'

SELECT  *
FROM    @User
WHERE   UserName LIKE REPLACE(@UserName, ' ', '%')
astander
+1 Looks good to me. If this works for kennethj, I'd choose this approach over the one I suggested.
AdaTheDev