How can i pass a string delimited by space or comma to stored procedure and filter result? I'm trying to do something like -
Parameter Value
--------------------------
@keywords key1 key2 key3
Then is stored procedure i want to first
- find all records with first or last name like key1
- filter step 1 with first or last name like key2
- filter step 2 with first or last name like key 3
Another example:
col1 | col2 | col3
------------------------------------------------------------------------
hello xyz | abc is my last name | and i'm a developer
hello xyz | null | and i'm a developer
If i search for any following it should return for each?
"xyz developer" returns 2 rows
"xyz abc" returns 1 row
"abc developer"returns 1 row
"hello" returns 2 rows
"hello developer" returns 2 rows
"xyz" returns 2 rows
You could try something like:
where @test is the table with results of your split. If you have lots of columns in persondata, you might want to just return an ID from this query, and use it as a subquery for the one that actually returns data, so you don't have to group by so many columns.
Edit: you could also use a cursor and another temp table/table variable, but I have kind of an allergic reaction to cursors in SPs.
Since you can't use a table parameter (not on SQL Server 2008), try passing in a CSV sting and have the stored procedure split it into rows for you.
There are many ways to split string in SQL Server. This article covers the PROs and CONs of just about every method:
"Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog
You need to create a split function. This is how a split function can be used:
I prefer the number table approach to split a string in TSQL but there are numerous ways to split strings in SQL Server, see the previous link, which explains the PROs and CONs of each.
For the Numbers Table method to work, you need to do this one time table setup, which will create a table
Numbers
that contains rows from 1 to 10,000:Once the Numbers table is set up, create this split function:
You can now easily split a space delimited string into a table and join on it or use it however you need This codes is based on the OPs latest question edit:
OUTPUT: