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
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
Numbersthat 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: