我必须在sql server中执行此操作
我有
等数据Belo Horizonte , MG - Brazil
São Paulo , SP - Brazil
Barueri , SP - Brazil
Ferraz de Vasconcelos , SP - Brazil
我需要选择两个字母单词,因为它匹配模式
Space Letter Letter
我试过这个
SUBSTRING(ADDRESS_BLOCK,PatIndex('% [A-Z][A-Z] %',ADDRESS_BLOCK),3)
但我需要考虑只有大写字母(即)输出必须是
MG SP SP SP
不包括示例de
Ferraz de Vasconcelos , SP - Brazil
清楚查看问题
例如:vaishnava st northwind GH - 结果必须是GH
somersert PM vailash hj --Result has to be PM
答案 0 :(得分:4)
试试这个:您需要整理列并指定大写字母。即使您指定了归类序列,正则表达式[A-Z]也不区分大小写。
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
答案 1 :(得分:1)
我认为这样做会......或其变体以满足您的需求。 。 在这种情况下,它将挑出第一对大写字母......
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
Aamer
答案 2 :(得分:0)
逗号后选择2个字母:
select substring(columnname, charindex(',', columnname) + 2, 2)
from tablename
或使用-
:
select substring(columnname, charindex('-', columnname) - 3, 2)
from tablename
最终,不优雅,解决方案:
SUBSTRING(ADDRESS_BLOCK,PatIndex('% [ABCDEFGHIJKLMOPQWXYZ][ABCDEFGHIJKLMOPQWXYZ] %',ADDRESS_BLOCK),3)
它选择两个大写字母。
答案 3 :(得分:0)
答案 4 :(得分:-1)
整理很重要。您需要在查询中添加Collate
,例如:
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;
您可能需要进行差异整理 - 您当前的整理显然不区分大小写。您可以找到当前的排序规则,并将Latin1_General_CS_AS_KS_WS
替换为您需要的排序规则,将CI
替换为CS
,以获得当前排序规则的案例敏感版本。