[英]SQL server separating first name, last name, and middle initial permanently
I have a table that has first name, last name, and middle initial, when there is one, in one column like this: 我有一个表,在这样的一列中有名字,姓氏和中间名首字母(如果有的话):
Name
Doe, John B
Smith, Bob
Some names do not have a middle initial and I just want to get rid of the ones that do. 有些名字没有中间的缩写,我只想除去那些名字的缩写。 So far I have this query:
到目前为止,我有这个查询:
SELECT [table].[Name]
,LEFT([table].[Name], CHARINDEX(',', [table].[Name]) - 1) AS [Surname]
,REPLACE(SUBSTRING([table].[Name], CHARINDEX(',', [table].[Name]), LEN([table].[Name])), ',', '') AS [FirstName]
FROM [table]
Which gives me this result: 这给了我这个结果:
Surname First Name
Doe John B
Smith Bob
Is there something that I can add to just get rid of the middle initial when it occurs? 有什么我可以添加的,以消除出现在中间的缩写吗? Also, can I permanently change this data so it remains in two separate columns?
另外,我可以永久更改此数据,使其保留在两个单独的列中吗?
Assuming the format is strictly Last, First <Optional initial>
for first without initial: 假设格式严格为
Last, First <Optional initial>
表示无首字母的首字母:
SUBSTRING([table].[Name], CHARINDEX(',', [table].[Name]) + 2,
LEN([table].[Name]) - CHARINDEX(',', [table].[Name])
- CASE WHEN PATINDEX('% [A-Z]', [table].[Name]) > 0 THEN 3 ELSE 0 END)
If you want to permanently change it, create a query with what you want and overwrite the values. 如果要永久更改它,请使用所需内容创建查询并覆盖值。
WITH CTE AS (SELECT Name, LEFT(Name,CHARINDEX(',',RIGHT(Name,LEN(Name)-CHARINDEX(',',Name)))+CHARINDEX(',',Name)-1) AS [Last] FROM table)
SELECT [Last], LEFT(REPLACE(Name,Last+', ',''),CHARINDEX(' ',REPLACE(Name,Last+', ',''))-1) AS [First],
RIGHT(REPLACE(Name,Last+', ',''),LEN(REPLACE(Name,Last+', ',''))-CHARINDEX(' ',REPLACE(Name,Last+', ',''))) AS Middle
FROM CTE
This uses a CTE for clarity and it also accounts for many special cases including names with suffixes (Jr, Sr, Esq, etc). 为了清晰起见,这使用了CTE,并且还考虑了许多特殊情况,包括带后缀的名称(Jr,Sr,Esq等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.