SQL - 按单词开头搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14778350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:34:38  来源:igfitidea点击:

SQL - search by beginning of a word

sqlextract

提问by tester2001

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

旅鼠有限责任公司

I can do this in PHP by extracting/slicing the string into an array and searching the beginning of each words. But how I would write this query in SQL server without resorting to Stored procedures/functions?

我可以通过将字符串提取/切片到数组中并搜索每个单词的开头来在 PHP 中执行此操作。但是我如何在不求助于存储过程/函数的情况下在 SQL 服务器中编写这个查询?

回答by chabzjo

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.)

(这是假设所有单词都用空格分隔。)

回答by John Woo

use LIKE

LIKE

SELECT * FROM tableName WHERE CompanyName LIKE 'Em%'

回答by ain

Another option is CONTAINS, something like:

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

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