I need to compare the end of lines with a list of possible endings in a stored procedure. It will be called a lot, and there are about 10-15 candidates. At the moment, a code-only solution is preferable to creating tables dedicated to this. Something that would look like:
IF (ENDSWITH(@var, 'foo') OR ENDSWITH(@var, 'bar') OR ENDSWITH(@var, 'badger') OR ENDSWITH(@var, 'snake')) ( )
I am looking for the best way in terms of speed, but also maintainability. The candidates that I know of are
CORRECTLY, my favorite so far, but that means I need to hardcode the length of the string, so it can be error prone. It also means repeatedly cutting the source string.
IF ((LEN(@var) >= 3 AND RIGHT(@var, 3) = 'foo')) OR ...
LIKE maybe slower but a little cleaner
IF (@var LIKE '%foo') OR ...
CHARINDEX is most likely slower as it searches for an entire string
SUBSTRING is most likely equivalent to RIGHT and much more ugly
SQLCLR to create my own ENDSWITH, it can be pretty fast
There may be better ways that I don't know about. What do you think?
optimization sql sql-server tsql string-comparison
Djof
source share