Best way to compare the end of a string, use RIGHT, LIKE or other?

*爱你&永不变心* 提交于 2019-12-04 10:34:45

问题


I need to compare the end of strings against a list of possible ending in a stored procedure. It will be called a lot and there are around 10-15 candidate endings. At this point a code-only solution is preferable to creating tables dedicated to this. Something that would be like:

IF (ENDSWITH(@var, 'foo') OR
    ENDSWITH(@var, 'bar') OR
    ENDSWITH(@var, 'badger') OR
    ENDSWITH(@var, 'snake'))
(
)

I'm looking for the best way in terms of speed, but also maintainability. Candidates that I know of are

  • RIGHT, my favorite so far but it means I have to hardcode the string length, so can be prone to error. It also means cutting the source string many times.

    IF ((LEN(@var) >= 3 AND RIGHT(@var, 3) = 'foo')) OR ...
    
  • LIKE, probably slower, but a bit cleaner

    IF (@var LIKE '%foo') OR ...
    
  • CHARINDEX, most probably slower since it searches the whole string

  • SUBSTRING, most probably equivalent to RIGHT and much more ugly

  • SQLCLR to create my own ENDSWITH, it can be pretty quick

There might be better ways I don't know of. What do you think?


回答1:


The best way to optimize this for SQL might be to store the REVERSE string value in another column that is indexed and search the left side of that using either LEFT or LIKE.




回答2:


also, you may use a combination of RIGHT and LENGTH so that you do not hardcode string length.




回答3:


Parsing strings will have an overhead, best suggestion is the LIKE '%foo' OR as an option. Certain indexes will take advanage and do Seeks over Scans.

You'd have to benchmark to see if suitable but would be easily testable.

Check this out regarding LIKE and INDEX http://myitforum.com/cs2/blogs/jnelson/archive/2007/11/16/108354.aspx



来源:https://stackoverflow.com/questions/7394276/best-way-to-compare-the-end-of-a-string-use-right-like-or-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!