我正在尝试使用子字符串,instr和charindex的组合,以一致地从组合字符串值中获取名称,格式如下:
"Lastname,Firstname MiddleName"
我必须能够考虑以下逻辑:
这是我到目前为止所拥有的
,SUBSTRING(p.Name,1,INSTR(p.Name,',',1) - 1) as "Patient Surname"
,SUBSTRING(p.Name,INSTR(p.Name,' ',1) + 1, INSTR(p.Name,' ')) as "Patient Middle Name"
,SUBSTRING(p.Name,INSTR(p.Name,',',1) + 1, INSTR(p.Name,' ')) as "Patient First Name"
我也尝试过类似的方法来获得名字。
,SUBSTRING(p.Name,charindex('','',p.Name)+1, charindex(',',reverse(p.Name))) as "Patient First Name"
我似乎对该姓氏充满信心。 名字和中间名是我正在努力捕捉的。有人可以帮忙吗?
以下是我需要处理的一些示例名称。
答案 0 :(得分:2)
declare @x as varchar(100) = 'Dinsmore,Archibald Hector';
SELECT LEFT(@x, CHARINDEX(',', @x) -1 ) as surname,
SUBSTRING(@x,
CHARINDEX(',', @x) + 1,
CHARINDEX(' ', @x, CHARINDEX(',', @X)) - CHARINDEX(',', @x) - 1
) as FirstName,
SUBSTRING(@x,
CHARINDEX(' ', @x, CHARINDEX(',', @X)) + 1 ,
CHARINDEX(' ', REVERSE(@X))) as middleName
好的,下面也可以处理中间名
declare @x as varchar(100) = 'Dinsmore,Archibald';
SELECT CHARINDEX(' ', @x, CHARINDEX(',', @X))
SELECT LEFT(@x, CHARINDEX(',', @x) -1 ) as surname,
CASE WHEN CHARINDEX(' ', @x, CHARINDEX(',', @X)) > 0 THEN
SUBSTRING(@x,
CHARINDEX(',', @x) + 1,
CHARINDEX(' ', @x, CHARINDEX(',', @X)) - CHARINDEX(',', @x) - 1
)
ELSE
RIGHT(@x, CHARINDEX(',', REVERSE(@X)) - 1)
END as FirstName,
CASE WHEN CHARINDEX(' ', @x, CHARINDEX(',', @X)) > 0 THEN
SUBSTRING(@x, CHARINDEX(' ', @x, CHARINDEX(',', @X)) + 1 , CHARINDEX(' ', REVERSE(@X)))
ELSE
NULL
END as middleName
答案 1 :(得分:0)
检查此代码:
table.find('tr').each(function (i) {
答案 2 :(得分:0)
我想这是最简单的解决方案。我通过在末尾添加空格来使用“技巧” 然后只有一种情况,其中存在名字,中间名和姓氏:)
SELECT
B.Name, SUBSTRING(B.Name,1,CHARINDEX(',', B.Name) - 1) as "Patient Surname"
,SUBSTRING(B.Name,CHARINDEX(' ', B.Name + ' ') + 1, CHARINDEX(' ', B.Name + ' ')) as "Patient Middle Name"
,SUBSTRING(B.Name, CHARINDEX(',', B.Name) + 1, CHARINDEX(' ', B.Name + ' ') - CHARINDEX(',', B.Name)) as "Patient First Name"
FROM
(
SELECT
'Lastname,Firstname MiddleName' AS Name
UNION
SELECT
'Lastname,Firstname' AS Name
) B
在sqlfiddle http://sqlfiddle.com/#!18/9eecb/27064/0上测试
更新 添加样本数据后 尤其是这张姓氏所在的记录
INSERT INTO P(Name) VALUES('St. Smurf,Baker');
我修改了答案
SELECT
P.Name, SUBSTRING(P.Name,1,CHARINDEX(',', P.Name) - 1) as "Patient Surname"
,SUBSTRING(P.Name, CHARINDEX(' ', P.Name + ' ', CHARINDEX(',', P.Name)) + 1, CHARINDEX(' ', P.Name + ' ', CHARINDEX(',', P.Name))) as "Patient Middle Name"
,SUBSTRING(P.Name, CHARINDEX(',', P.Name) + 1, CHARINDEX(' ', P.Name + ' ', CHARINDEX(',', P.Name)) - CHARINDEX(',', P.Name)) as "Patient First Name"
FROM
P
在sqlfiddle上获得示例数据的结果 http://sqlfiddle.com/#!18/e525d/4/0