简体   繁体   中英

Search for arbitrary strings and not just prefix in T-SQL

My requirement is to be able to search strings in column which match any number of characters in order against the passed string.

For example:

If I passed Hello and if my table column has Tell than query should select Tell for matching ll in two strings. While it can give results for match of single character as well since there can be no order in it. but if its two characters matching ,than those two have to be consecutive, not picked out randomly from any position ie in you and our , its a two character match because ou is present in both strings in same order. What I have considered so far is using Substring in my query until the length of loop ie

while begin(@counter <= lengthOfPassedString)
   select Name from column where column LIKE + '%' + SUBSTRING(@parameterFromUser, 1, @counter) + '%' 
end

But above code can look for brook in Westbrook but can not look for rook from krook if I passed krook as the string and westbrook was present in column of table.

Shall I consider using nested while loop with counter for starting position of SUBSTRING method as well? I understand the performance will be (lengthofstring)^2 but would love to get to know a better approach for this.

Assuming you need to match at least two characters, here is a brute force method which does not require loops:

It only works for inputs up to 9 characters long. I think you get the idea.

This is the only non loop solution that I can think of. You might be able to do some crazy FOR XML thing but I think that's over the top.

You can also use a CTE or select from a system table to generate a tally table and use that just like a loop. Let me know if you would like to see that solution.

declare @p varchar(50)
SET @p = 'Krook'

select * from 
(
select 'Westbrook' G
UNION ALL
select 'Tell' G
UNION ALL
select 'Something' G
) F
where (
f.G LIKE REPLACE('%' + substring(@p,1,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,2,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,3,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,4,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,5,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,6,2) + '%','%%','')
OR
f.G LIKE REPLACE('%' + substring(@p,7,2) + '%','%%','')
)

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