Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL substring - separating first and last name

I have a column which has FirstName and LastName together. I'm writing a report to separate the FirstName And LastName. How do I get the FirstName and LastName separated in T-SQL?

like image 396
user1440697 Avatar asked Jun 06 '12 20:06

user1440697


People also ask

How do I separate first name and last name in SQL?

Using SUBSTRING Function The CHARINDEX function returns the starting position of a specified expression in a character string. The CHARINDEX function was used to look for the space that separates the first name from the last name (CHARINDEX(' ', @FullName)).

How do you split first middle and last name in SQL?

substr((replace(fullname,(substr(fullname,1, instr(fullname,' '))),'')),instr((replace(fullname,(substr(fullname,1, instr(fullname,' '))),'')),' ')+1) Last_Name from fullnames; Note---> fullnames is a table name and fullname is a column name.

How do I split a string in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.

How split a string by space in SQL?

Used WHERE CHARINDEX(' ',ltrim(rtrim(fieldname))) = 0 which works fine ! @huMptyduMpty - You got it. =0 will give you items with one word, >0 will give you items with two words -- and yes, if you have leading in or trailing spaces those will need to be removed.


2 Answers

Assuming the FirstName is all of the characters up to the first space:

SELECT   SUBSTRING(username, 1, CHARINDEX(' ', username) - 1) AS FirstName,   SUBSTRING(username, CHARINDEX(' ', username) + 1, LEN(username)) AS LastName FROM   whereever 
like image 62
bluevector Avatar answered Sep 25 '22 13:09

bluevector


The easiest way I can find to do it is:

SELECT    SUBSTRING(FullName, 1, CHARINDEX(' ', FullName) - 1) AS FirstName,   REVERSE(SUBSTRING(REVERSE(FullName), 1, CHARINDEX(' ', REVERSE(FullName)) - 1)) AS LastName FROM   [PERSON_TABLE] 
like image 32
Rui de Almeida Avatar answered Sep 21 '22 13:09

Rui de Almeida