Concat First Middle and Last name in Sql

Concat First Middle and Last name in Sql

Concat First Middle and Last name in Sql

Hey folks till now we have discussed Performance improvement of cursor SQL ServerUser defined functions in sqlKill Processes in sql server 2008, View in sql default constraint in sql , Remove Cross duplicate rows in SQLRecursive SQL Query , Recursive SQL Query-2STUFF and CONCAT in SQLRANK in SQL server , Difference between temporary table and table variable in sql serverUNIQUEIDENTIFIER in SQL ServerRAW Mode with FOR XML , AUTO Mode with FOR XMLEXPLICIT Mode with FOR XML , PATH Mode with FOR XMLOUTPUT Clause in SQL ServerDifference between delete and truncate in sql server etc.

Today I am going to explain very important concept, how to Concatenation of First Middle and Last name in Sql  and how could we handle NULL values and discard extra spaces from concatenation.

Lets check with below sample code:

DECLARE @firstname VARCHAR(MAX)='FirstName'
DECLARE @middlename VARCHAR(MAX)=NULL
DECLARE @lastname VARCHAR(MAX)='Last'

--Query solution 1
SELECT '|'+RTRIM(LTRIM(RTRIM(isnull(@firstname,'') 
                     + ' ' + isnull(@middlename,'')) 
                     + ' ' + isnull(@lastname,'')))+'|'
                     
--Query solution 2
SELECT '|'+RTrim(Coalesce(@firstname + ' ','') 
+ Coalesce(@middlename + ' ', '')
+ Coalesce(@lastname + ' ', '')
)+'|'

 

Concat First Middle and Last name in Sql

 

 

 

Leave a Reply