Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine first name, middle name and last name in SQL server

Tags:

sql-server

you can refer the below queries to get the same-

1

select FirstName +' '+ MiddleName +' ' + Lastname as Name from TableName.

2

select CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) as Name from 
  TableName

3

select Isnull(FirstName,' ') +' '+ Isnull(MiddleName,' ')+' '+ Isnull(Lastname,' ') 
from TableName.

Note: Point 1 query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL" value.

To avoid the point number 1, you can use point number 2 or point number 3 -

We can use IsNull or CONCAT keyword to get the same.

If anyone containing null value then ' ' (blank space) will add with next value.

like image 525
Ritesh Yadav Avatar asked Feb 02 '18 06:02

Ritesh Yadav


People also ask

How do I concatenate my first name and last name?

Let's say you want to create a single Full Name column by combining two other columns, First Name and Last Name. To combine first and last names, use the CONCATENATE function or the ampersand (&) operator.

How do I combine first name middle name and last name in Oracle?

For Oracle it is : Select firstname+' '+lastname from emp; or select concat(firstname,lastname) Name from emp; (As far as I remember concat in oracle can not take more than two arguments). So if you want to concatenate more than two fields it is better to use the concatenation operator.


2 Answers

  • Using a combination of RTRIM and LTRIM will strip any white-space on each end.
  • CONCAT to append the name segments together
  • COALESCE to replace NULL with an empty string

Formatted for readability

SELECT 
    RTRIM(LTRIM(
        CONCAT(
            COALESCE(FirstName + ' ', '')
            , COALESCE(MiddleName + ' ', '')
            , COALESCE(Lastname, '')
        )
    )) AS Name
FROM TableName
like image 66
seantunwin Avatar answered Oct 19 '22 00:10

seantunwin


Replace function removes two character white-spaces while concatenating First, Middle and Last Name.

SQL2016 and above compatible code

SELECT REPLACE(CONCAT(FirstName+' ',MiddleName+' ',LastName+' '),'  ',' ') 
AS EmployeeName
FROM dbo.Employee

SQL SERVER 2017 Compatible code:

  SELECT REPLACE(CONCAT_WS(' ',FirstName,MiddleName,LastName),'  ',' ')AS 
  EmployeeName FROM dbo.Employee 
like image 13
Sameer Avatar answered Oct 19 '22 02:10

Sameer