我忍不住尝试了这个。以下代码适用于 SQL Server,它确实有效(您可以在 sqlfiddle 上查看)。
这是一个多步骤的过程。这个想法是通过加入一堆数字并检查字符的值来确定名称中每个大写字母的位置,以查看它是否大写。每个大写字母都在自己的行中。
然后,为此提取名称部分并将每个字符串的字符串连接在一起。此方法有效,假设第一个字母大写(如果不是这种情况,很容易修复)。
另外,请记住一些大写字母不是“边缘”:“McGarvey”、“Chen-Smith”等等。
这些步骤中的每一个都将因数据库而异。
with somenums as (
select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
),
nums as (
select ROW_NUMBER() over (order by (select NULL)) as n
from somenums s cross join somenums s2
),
test as (
select 'JohnAlanSmith' as name union all
select 'MaryElizabethChou'
),
caps as (
select name, n
from test join
nums
on ascii(SUBSTRING(test.name, nums.n, 1)) between ascii('A') and ascii('Z')
),
nameparts as (
select name, n, nextn, SUBSTRING(name, n, coalesce(nextn - n, 1000)) as namepart
from (select name, n,
(select min(n) from caps c2 where c2.name = c.name and c2.n > c.n
) as nextn
from caps c
) c
)
select name,
STUFF((select ' '+namepart
from nameparts np2
where np2.name = np.name
order by n
for xml path ('')
), 1, 1, ''
) as betterName
from nameparts np
group by name