简体   繁体   English

SQL - 按单词开头搜索

[英]SQL - search by beginning of a word

I want to write an SQL SERVER statement that searches for the beginning of a word in a string that starts with something. 我想编写一个SQL SERVER语句,用于搜索以某些内容开头的字符串中单词的开头。

For example, if I search for 'em' on the Company record, I should get: 例如,如果我在公司记录中搜索'em',我应该得到:

Emily, Inc 艾米莉公司

The Emmmy 艾美奖

NOT

Forget Them 忘记他们

Lemming, LLC Lemming,LLC

I can do this in PHP by extracting/slicing the string into an array and searching the beginning of each words. 我可以通过将字符串提取/切片成数组并搜索每个单词的开头来在PHP中完成此操作。 But how I would write this query in SQL server without resorting to Stored procedures/functions? 但是如何在不借助存储过程/函数的情况下在SQL服务器中编写此查询?

JW's answer will work for entries where Em is at the very beginning of the field. JW的答案适用于Em处于该领域最开始的条目。

If you also need to retrieve values where the word is not the first in the string, try: 如果您还需要检索单词不是字符串中第一个的值,请尝试:

SELECT * FROM tableName WHERE CompanyName LIKE 'Em%' or CompanyName LIKE '% Em%'

(This is assuming all word are separated by a space.) (这假设所有单词都用空格分隔。)

使用LIKE

SELECT * FROM tableName WHERE CompanyName LIKE 'Em%'

另一种选择是CONTAINS ,类似于:

SELECT ... WHERE CONTAINS(CompanyName, 'Em*');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM