If you haven't used OPENXML before it is available in SQL Server 2005/2008 and is really quite useful. In the past, I have used this mostly for passing in multiple objects to perform a mass INSERT and/or UPDATE. This was my first time using it with a LIKE statement, but it works perfectly. I didn't want to lose this code, since I am likely to use it again in the future so I figured I would do a quick blog post. So here is how to pass multiple parameters into a LIKE statement in SQL Server.
Below the schema for a table that I will use in my example.
Here is a little sample data for as well
So I need to be able to search the "Bio" field in my table to see if it contains the words 'PhD', 'scientist' or 'CEO'.
First, I need to build my search terms in XML form. This is a simple string which can be built in your application code and passed as a parameter into SQL Server. My example below show how you can do it in SQL Server so you can tweak it.
--String parameter with the search terms in XML formatOne key thing to note is that this must be done via a JOIN, otherwise it will not work. The JOIN is what allows the LIKE comparison over multiple criteria dynamically.
DECLARE @xmlTerms VARCHAR(8000) -- Size it according to your expectations
--Here I am building the XML string with all the necessary terms.
SET @xmlTerms =
'<SearchTerms>
<SearchTerm>%PhD%</SearchTerm>
<SearchTerm>%scientist%</SearchTerm>
<SearchTerm>%CEO%</SearchTerm>
<SearchTerms>'
--A handle to the XML so we can reference it in the OPENXML call
DECLARE @xmlHandle INT
--This parses the XML and returns us a handle to the data
EXEC sp_xml_preparedocument @xmlHandle out, @xmlTerms
--Now we can perform our query
SELECT id, searchTerm FROM exampleTable A
INNER JOIN (SELECT searchTerm
FROM OPENXML(@xmlHandle,'/SearchTerms/SearchTerm',1) --Make note that the XML nodes are case sensitive
WITH (searchTerm VARCHAR(50) 'text()')) T ON A.Bio LIKE searchTerm
ORDER BY id



