开发者

Phrase Search in SQL Server 2008 (T-SQL)

开发者 https://www.devze.com 2023-03-30 21:54 出处:网络
I have a v开发者_运维问答archar column with 3 rows: i eat orange, orange, oranges are nice I want SELECT query to return the result in this order:

I have a v开发者_运维问答archar column with 3 rows:

i eat orange,
orange,
oranges are nice

I want SELECT query to return the result in this order:

orange, oranges are nice, i eat orange

i.e. those matches that start with the 'keyword'=orange should come before those that contain the keyword which again should come before those that ends with the keyword.

How can I do this using T-SQL? I tried using the LIKE keyword but no success so far.


 WHERE column LIKE '%' + keyword + '%'
 ORDER BY CASE WHEN column = keyword THEN 0
               WHEN column LIKE keyword + '%' THEN 1
               WHEN column LIKE '%' + keyword + '%' THEN 2 END

But really, for this kind of search you want to use a full-text index.


Try the following order by clause (assuming your WHERE clause returns only matches)

ORDER BY charIndex(keyword,col_name),length(col_name)

This will put the earliest occurrence of the keyword first.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号