Reputation: 1
I want to select first 4 letters of the address string ignoring the numbers or P.O. box.
For example, I have a database column "address" in "customers" table.
51 church st
In a query, I only want "chur" ignoring the numbers. It can be any number. I am not interested in number. Also, I don't want this for just one record. I want this to happen for every record So for example I have these records:
51 church st
6178 fookeral ave
597537 state ct
In my 1 query i want results look like this
Chur
Fook
Stat
How can I get this in one query?
Upvotes: 0
Views: 1450
Reputation: 44911
As an alternative to CHARINDEX
you could use PATINDEX and have it match any character in the a-z
range:
SELECT SUBSTRING(address, PATINDEX('%[a-z]%', address), 4) AS FirstFour
FROM customers
This would give the correct result if you have any address like 51 32 church st
, that is with a number followed by a space followed by another number.
This solution assumes you use Microsoft SQL Server.
Edit: added a solution for Oracle (tested with 11g R2).
In Oracle you can use regular expressions and the REGEXP_SUBSTR function like this:
SELECT
REGEXP_SUBSTR("Address",'[[:alpha:]]{4}') "FourChars",
INITCAP(REGEXP_SUBSTR("Address",'[[:alpha:]]{4}')) "FourCharsInitCap"
FROM customers
This returns:
FOURCHARS FOURCHARSINITCAP
chur Chur
fook Fook
stat Stat
Upvotes: 1