简体   繁体   English

sql-拆分姓氏和名字

[英]sql - split first and last name

I need to split all names into first and last. 我需要将所有名字分为姓氏和名字。

I have the names in the same column and the names have several words. 我在同一列中有名字,名字有几个词。 For example 例如

table1

Nome
____________________________________
Abel da Silva Barros                                   
Abel da Silva Dias                                     
Abilio Rodrigo Garcia da Silva Costa                   
Adelino David Oliveira Silva                           
Ademar Adolfo Lopes Gomes                              
Adriano Leonel Fernandes Castro Goncalves              
Agostinho Alberto Pereira Duarte                       
Agostinho Fernando Nogueira Pereira                    
Aires Manuel Oliveira da Costa                         
Alberto Costa                                          
Alberto Sergio Oliveira Dias Silva                     
Albino Mouta de Sousa                                  
Alfredo de Sousa Barreto                               
Alfredo Guilherme Gonçalves Cerqueira                  
Alfredo Magalhães Queiros                              
Alfredo Miguel Pereira Goncalves Vieira da Silva  

I need the output like this, only the fist and last name! 我需要这样的输出,只有拳头和姓氏!

Abel Barros
Abel Dias
Abilio Costa
Adelino Silva
Ademar Gomes
Adriano Gonçalves
Agostinho Duarte
...

How can i do this in MS SQL 2016 我如何在MS SQL 2016中执行此操作

Thanks on advance 提前谢谢

You could try using left, right and charindex 您可以尝试使用left,right和charindex

 SELECT LEFT(your_col, charindex(' ', your_col) - 1) , 
       RIGHT(your_col, CHARINDEX (' ' ,REVERSE(your_col))-1)
from your_table

You can do the following. 您可以执行以下操作。

First split string before the space separator 空格分隔符前的第一个分割字符串

SUBSTRING(Nome, 0, CHARINDEX(' ', Nome))

Then split string at the last occurence 然后在最后一次出现时分割字符串

SUBSTRING( Nome , LEN(Nome) -  CHARINDEX(' ',REVERSE(Nome)) + 2  , LEN(Nome))

Concatenate both with the following + ' ' + 用以下+ ' ' +

SELECT SUBSTRING(Nome, 0, CHARINDEX(' ', Nome)) + ' ' +
SUBSTRING( Nome , LEN(Nome) -  CHARINDEX(' ',REVERSE(Nome)) + 2  , LEN(Nome)  )
FROM table1;

Test here : http://sqlfiddle.com/#!6/f54391/1 在这里测试: http : //sqlfiddle.com/#!6/f54391/1

Just in case other see this and needs SQL Server 2008 (or older). 以防万一其他人看到这并需要SQL Server 2008(或更早版本)。

You can modify the answer from scaisEdge to take care of single word-names, without using IIF (introduced in SQL Server 2012) 您可以修改scaisEdge的答案以使用单个单词名称,而无需使用IIF(在SQL Server 2012中引入)

Simply add a space after name, when looking for first name, and add a space before name when looking for last name. 在查找名字时,只需在名称后添加一个空格,在查找姓氏时,在名称前添加一个空格。 replace co.Name with your actual column name. 用您的实际列名替换co.Name。

LEFT(co.Name, charindex(' ', co.Name+' ') - 1) firstname, 
RIGHT(co.Name, CHARINDEX (' ' ,REVERSE(' ' + co.Name))-1) lastname,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM