开发者

Index for wildcard match of end of string

I have a table of phone numbers, storing the phone number as varchar(20). I have a requirement to implement searching of both entire numbers, but also on only the last part of the number, so a typical query will be:

SELECT * FROM PhoneNumbers WHERE Number LIKE '%1234'

How can I put an index on the Number column to make those searchs eff开发者_开发知识库icient? Is there a way to create an index that sorts the records on the reversed string? Another option might be to reverse the numbers before storing them, which will give queries like:

SELECT * FROM PhoneNumbers WHERE ReverseNumber LIKE '4321%'

However that will require all users of the database to always reverse the string. It might be solved by storing both the normal and reversed number and having the reversed number being updated by a trigger on insert/update. But that kind of solution is not very elegant.

Any other suggestions?


ALTER TABLE phonenumbers ADD reverse_number AS REVERSE(number) PERSISTED

CREATE INDEX ix_phonenumbers_reversenumber ON phonenumbers (reverse_number)

SELECT  *
FROM    phonenumbers
WHERE   reverse_number LIKE '4321%'


You don't need to have the users reverse unless they are manually executing the query and you can use a computed column rather than a trigger:

CREATE TABLE TBL (TEL VARCHAR(20) NOT NULL)
ALTER TABLE TBL ADD TEL_REV AS REVERSE(TEL)
CREATE NONCLUSTERED INDEX IX_REVERSETEL ON TBL (TEL_REV) INCLUDE (TEL)

INSERT TBL SELECT '12345678'
    UNION SELECT '147258369'
    UNION SELECT '963852741'

--find nums ending in 5678
SELECT * FROM TBL WHERE TEL_REV LIKE REVERSE('5678') + '%' /*index seek*/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜