How to fetch entries starting with the given string from a SQL Server database?

↘锁芯ラ 提交于 2019-12-04 23:36:04

When using like, you provide a % sign as a wildcard. If you want strings that start with Hello, you would use LIKE 'Hello%' If you wanted strings with Hello anywhere in the string, you would use LIKE '%Hello%'

As for efficiency, using Like is not optimal. You should look into full text search.

I know of the LIKE command, but it seems to me that it is more of an EQUAL command. I get only the words that looks exactly like the word I enter.

That's because you aren't using wildcards:

WHERE column LIKE 'abc%'

...will return rows where the column value starts with "abc". I'll point out that when using wildcards, this is the only version that can make use of an index on the column... er column.

WHERE column LIKE '%abc%'

...will return rows where the column value contains "abc" anywhere in it. Wildcarding the left side of a LIKE guarantees that an index can not be used.

SQL Server doesn't natively support regular expressions - you have to use CLR functions to gain access to the functionality. But it performs on par with LIKE.

Full Text Search (FTS) is the best means of searching text.

You can also implement a StartWith functionality using the following statements:

LEFT('String in wich you search', X) = 'abc'

CHARINDEX('abc', 'String in wich you search') = 1

'String in wich you search' LIKE 'abc%'

Use the one wich performs best.

You can use CONTAINS in T-SQL, but I'm pretty sure you have to have to be using full-text indexing for the table involved in your query.

Contains

Getting started with Full-Text Search

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