Proper / title case in t-sql

时光总嘲笑我的痴心妄想 提交于 2019-12-05 11:46:50

Proper case is something that is so hard to get right. Think names like Van der Wilden and VanWyck. I wrote a T-SQL function years ago but other than going with CLR there really isn't anything new in SQL Server 2012 that will help with this:

http://web.archive.org/web/20120215192418/http://classicasp.aspfaq.com/general/how-do-i-convert-a-name-to-proper-case.html

P.S. why are you still using RC0? RTM (11.0.2100) was released today...

jhealytsst

If you have MDS installed (SQL 2005 and up) you could handle case properly through regular expressions.

You would need to add a bit more to it to handle the mentioned "Van der Wilden" but it could be extended to even handle this as well.

CASE 
WHEN mds.mdq.RegexIsMatch([First Name],'[A-Z]{1,}(\s|\-)[A-Z]{2,}',7)=1 THEN

UPPER(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)(\s|\-)','First',7),1,1))+lower(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)(\s|\-)','First',7),2,LEN(mds.mdq.RegexExtract([First Name],'(?<First>.*)(\s|\-)','First',7))-1))
+ mds.mdq.RegexExtract([First name],'(?<Sep>(\s|\-))','Sep',7) + SUBSTRING(mds.mdq.RegexExtract([First Name],'(\s|\-)(?<MI>.*)','MI',7),1,1)+ LOWER(SUBSTRING(mds.mdq.RegexExtract([First Name],'(\s|\-)(?<MI>.*)','MI',7),2,LEN(mds.mdq.RegexExtract([First Name],'(\s|\-)(?<MI>.*)','MI',7))-1))

WHEN mds.mdq.RegexIsMatch([First Name],'[A-Z]{1,}\s[A-Z]{1}',7)=1 THEN

UPPER(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)\s','First',7),1,1))+
lower(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)\s','First',7),2,LEN(mds.mdq.RegexExtract([First Name],'(?<First>.*)\s','First',7))-1))
+ ' ' + mds.mdq.RegexExtract([First Name],'\s(?<MI>.*)','MI',7)+'.'
ELSE
UPPER(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)','First',7),1,1))+
LOWER(SUBSTRING(mds.mdq.RegexExtract([First Name],'(?<First>.*)','First',7),2,LEN(mds.mdq.RegexExtract([First Name],'(?<First>.*)','First',7))-1))
END 
,
[Last Name]=CASE
WHEN mds.mdq.RegexIsMatch([Last Name],'(\s|\-)',7)=1
THEN
SUBSTRING(mds.mdq.RegexExtract([Last Name],'(?<Maiden>.*)(\s|\-)','Maiden',7),1,1)+LOWER(SUBSTRING(mds.mdq.RegexExtract([Last Name],'(?<Maiden>.*)(\s|\-)','Maiden',7),2,LEN(mds.mdq.RegexExtract([Last Name],'(?<Maiden>.*)(\s|\-)','Maiden',7))-1))+
mds.mdq.RegexExtract([last name],'(?<Sep>(\s|\-))','Sep',7)+
SUBSTRING(mds.mdq.RegexExtract([Last Name],'(\s|\-)(?<Maiden>.*)','Maiden',7),1,1)+LOWER(SUBSTRING(mds.mdq.RegexExtract([Last Name],'(\s|\-)(?<Maiden>.*)','Maiden',7),2,LEN(mds.mdq.RegexExtract([Last Name],'(\s|\-)(?<Maiden>.*)','Maiden',7))-1))
Else
SUBSTRING([Last Name],1,1) +LOWER(SUBSTRING([last name],2,LEN([Last Name])-1))
END 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!