firstname和lastname大写的第一个字母

时间:2016-10-18 12:33:54

标签: sql sql-server tsql

假设我有一张满是名字的桌子。

单个单元格中的firstname.lastname。

如何将这些分隔为"名字姓氏",首字母大写?使用TSQL

样品:

  

mike.mikeson - > Mike Mikeson

     

katy.lumberjack - > Katy Lumberjack

3 个答案:

答案 0 :(得分:3)

其中一次,我们可以使用ParseName功能获得收益;-)

SELECT original_value
     , forename
     , surname
     , Upper(SubString(forename, 1, 1)) + Lower(Substring(forename, 2, 8000)) AS formatted_forename
     , Upper(SubString(surname , 1, 1)) + Lower(Substring(surname , 2, 8000)) AS formatted_surname
FROM   (
        SELECT name AS original_value
             , ParseName(name, 2) AS forename
             , ParseName(name, 1) AS surname
        FROM   (
                VALUES ('mike.mikeson')
                     , ('katy.lumberjack')
               ) AS users (name)
       ) AS step1

答案 1 :(得分:1)

以下将回答您的问题,但正如评论所指出的那样,您可能还需要考虑在任一部分中包含多个大写字母的名称,例如Mary-Anne McDonald,或者那些只是#39; t符合你的惯例。

declare @a table (Name nvarchar(50))
insert into @a values
 ('fred.bloggs')
 ,('john.doe')
 ,('alan.smith')

select Name
    ,upper(left(Name,1))
        + substring(Name,2,charindex('.',Name,1)-2)
        + ' '
        + upper(substring(Name,charindex('.',Name,1)+1,1))
        + right(Name,len(Name) - charindex('.',Name,1)-1)
        as FormattedName
from @a

答案 2 :(得分:0)

您可以尝试使用concat和substring,如下所示

declare @name varchar(50) = 'firstname.lastname'

select case when charindex('.',@name) > 0 then  concat(upper(left(@name,1)), substring(@name,2,charindex('.',@name)-2), ' ', upper(substring(@name,charindex('.',@name)+1,1)), substring(@name,charindex('.',@name)+2, len(@name)))
            else concat(upper(left(@name,1)), substring(@name,2,len(@name))) end