我有一个表tblPerson
和列fullname
--------------
fullname
--------------
Garcia, John C.
Herdan, Stephen S.
Ubico, Ed Z.
我想爆炸全名列以获取最后一个,第一个和中间名并分别创建3个列。
我正在使用MS SQL Server 2008 R2
输出:
------------------------------------------------------------------------
fullname lname fname mname
------------------------------------------------------------------------
Garcia, John C. Garcia, John C.
Herdan, Stephen S. Herdan, Stephen S.
Ubico, Ed Z. Ubico, Ed Z.
提前感谢
答案 0 :(得分:3)
最简单的解决方案是,
SELECT fullname,REVERSE(PARSENAME(REPLACE(REVERSE(fullname) ,' ' ,'.') ,1)) AS lname
,REVERSE(PARSENAME(REPLACE(REVERSE(fullname) ,' ' ,'.') ,2)) AS fname
,REVERSE(PARSENAME(REPLACE(REVERSE(fullname) ,' ' ,'.') ,3)) AS mname
FROM tblPerson
或强>
SELECT fullname,REVERSE(PARSENAME(REPLACE(REVERSE(fullname) ,' ' ,'.') ,1)) AS lname
,REVERSE(PARSENAME(REPLACE(REVERSE(fullname) ,' ' ,'.') ,2)) AS fname
,STUFF(fullname, 1, Len(fullname) +1- CHARINDEX(' ',Reverse(fullname)), '') mname
FROM tblPerson
答案 1 :(得分:1)
这个将支持多字的姓氏和名字:
$rootScope
答案 2 :(得分:1)
尝试;
;with data_tbl as (
select [fullname],
CHARINDEX(',', [fullname]) + 1 index_comma,
CHARINDEX(' ', [fullname], CHARINDEX(',', [fullname]) + 2) index_space,
len([fullname]) len_name
from tblPerson
--where [fullname] like '%, % %'
)
select
[fullname],
left([fullname], index_comma - 1) lname,
substring([fullname], index_comma, index_space - index_comma) fname,
substring([fullname], index_space, len_name) mname
from data_tbl
如果您添加where条件where [fullname] like '%, % %'
,那么它将忽略fromat fullname
%, % %