Thursday, June 14, 2012

How to exchange the two word of one column data using sql.

Introduction:
                     Here I am going to discussion about how to exchange the word of one column data using sql.

Some days back i had one Problem arise where i need to exchange the word of column data.In actual seniorio is like this ...In one table Users one column name Full Name is there where "FirstName LastName" stored but while displaying data I have to display "LastName FirstName".In this seniorio i have to apply the below querry to get the results.

The Users Table is Like this.



Now Apply below Querry.

Select SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50) + ' ' + SUBSTRING(FullName,0,CHARINDEX(' ',FullName,0)) as "LastName-FirstName" from  Users

Here i used the Substring where first substring will fetch the second word(LastName) and the second substring will fetch the first word(FirstName) and then i have concat it  both and name the column name "LastName-FirstName".

SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50)=CHARINDEX(' ',FullName) will find the string after space.means second word to end of string

CHARINDEX(' ',FullName,0)=this one string will start from index 0 to space will found means First word


The Output will be 


0 comments:

Post a Comment