Monday, September 10, 2012

Split first word from a field in SQL table

We can use SUBSTRING and CHARINDEX functions to split the first word from a value in SQL.
As an example, if there is a field as FullName in UserInfo table and if we want to get the first word of it, then we can use the below query to get it.

   1: SELECT  FullName , SUBSTRING( FullName ,0,CHARINDEX(' ',Name+' ',0)) AS FirstName
   2: FROM            dbo.UserInfo

In the CHARINDEX function I added ' ' to it, because otherwise it will return null if the FullName value only has a single word.

No comments:

Post a Comment