Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - search by beginning of a word

Tags:

sql

extract

I want to write an SQL SERVER statement that searches for the beginning of a word in a string that starts with something.

For example, if I search for 'em' on the Company record, I should get:

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?

like image 452
tester2001 Avatar asked Feb 08 '13 17:02

tester2001


2 Answers

JW's answer will work for entries where Em is at the very beginning of the field.

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 image 136
chabzjo Avatar answered Sep 27 '22 21:09

chabzjo


use LIKE

SELECT * FROM tableName WHERE CompanyName LIKE 'Em%'
like image 27
John Woo Avatar answered Sep 27 '22 21:09

John Woo