I have to do this in SQL Server
I have data such as
Belo Horizonte , MG - Brazil
São Paulo , SP - Brazil
Barueri , SP - Brazil
Ferraz de Vasconcelos
Collation matters. You need to add Collate
to your query, such as:
Select * from table where exists (Select SUBSTRING(ADDRESS_BLOCK,PatIndex('% [A-Z][A-Z] %',ADDRESS_BLOCK),3) from table)
COLLATE Latin1_General_CS_AS_KS_WS ASC;
You may need a difference collation - your current one is clearly case insensitive. You can find you current collation, and replace Latin1_General_CS_AS_KS_WS
with the one you need, replacing the CI
with CS
, to get the case senstive version of your current collation.
See: http://msdn.microsoft.com/en-us/library/ms184391.aspx
I think this will do it... or a variation thereof to suit your needs. In this case it'll pick out the first pair of of uppercase letters.
with dataset as
(
select 'Belo Horizonte , MG - Brazil' as val union all
select 'São Paulo , SP - Brazil' as val union all
select 'Ferraz de Vasconcelos , SP - Brazil'
)
select Substring(val ,PatIndex('%[A-Z][A-Z] %' COLLATE LATIN1_gENERAL_BIN,val),3)
from dataset
Could you just try this:
SUBSTRING([ADDRESS_BLOCK],PatIndex('%, [A-Z][A-Z] -%',[ADDRESS_BLOCK])+2,2)
Example
Select 2 leters after comma:
select substring(columnname, charindex(',', columnname) + 2, 2)
from tablename
or using -
:
select substring(columnname, charindex('-', columnname) - 3, 2)
from tablename
Final, not elegant, solution:
SUBSTRING(ADDRESS_BLOCK,PatIndex('% [ABCDEFGHIJKLMOPQWXYZ][ABCDEFGHIJKLMOPQWXYZ] %',ADDRESS_BLOCK),3)
It selects two uppercase letters.
Try this: You need to both collate the column AND specify the capital letters. The regular expression [A-Z] is not case sensitive, even if you specify a collation sequence.
SELECT SUBSTRING(
ADDRESS_BLOCK
, PatIndex(
N'% [ABCDEFGHIJKLMNOPQRSTUVWXYZ][ABCDEFGHIJKLMNOPQRSTUVWXYZ] %'
, ADDRESS_BLOCK COLLATE sql_latin1_general_cp1_cs_as
)
, 3
)
FROM
(
SELECT 'Belo Horizonte , MG - Brazil' ADDRESS_BLOCK
UNION
SELECT 'São Paulo , SP - Brazil'
UNION
SELECT 'Barueri , SP - Brazil'
UNION
SELECT 'Ferraz de Vasconcelos , SP - Brazil'
) n