简体   繁体   中英

SQL: creating a string array and query = like all strings in array

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?

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.

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, ' ', '%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM