Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Substring from a Name feild

Author  Topic 

jim_jim
Constraint Violating Yak Guru

306 Posts

Posted - 2013-09-24 : 13:45:21
Hi All
We capture the firstname of a person along with their middle intial in our contacts table . How do i use the substring function to get just the firstname and omit the middle initial

Sample Data

Jennifer K
Jason R
Samuel V

I want just the firstname without the space and middle initial

Required Format
Jennifer
Jason
Samuel

Thanks

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-09-24 : 15:19:15
[code]LEFT(YourNameColumn,CHARINDEX(' ',YourNameColumn+' '))[/code]This will produce wrong results if there are first names with spaces in them. If there is the possibility that there are spaces at the beginning, you would need to do an LTRIM before using this.
Go to Top of Page

sigmas
Posting Yak Master

172 Posts

Posted - 2013-09-24 : 17:11:25
quote:
How do i use the substring function to get just the firstname and omit the middle initial


substring(value, 1, len(value) - 2)
Go to Top of Page

mohan123
Constraint Violating Yak Guru

252 Posts

Posted - 2013-09-25 : 01:32:13
You can do like this also :
Declare @vc_Name VARCHAR(20) = 'Jennifer K'

SET @vc_Name = SUBSTRING (@vc_Name,1,CHARINDEX(' ',@vc_Name)-1)
SELECT @vc_Name

P.V.P.MOhan
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-09-25 : 07:56:52
quote:
Originally posted by mohan123

You can do like this also :
Declare @vc_Name VARCHAR(20) = 'Jennifer K'

SET @vc_Name = SUBSTRING (@vc_Name,1,CHARINDEX(' ',@vc_Name)-1)
SELECT @vc_Name

P.V.P.MOhan


Will break for cases where field doesnt have an initial.

try


Declare @vc_Name VARCHAR(20) = 'Jennifer'

SET @vc_Name = SUBSTRING (@vc_Name,1,CHARINDEX(' ',@vc_Name)-1)
SELECT @vc_Name


to make it work always you need to tweak it like

Declare @vc_Name VARCHAR(20) = 'Jennifer K'

SET @vc_Name = SUBSTRING (@vc_Name,1,CHARINDEX(' ',@vc_Name+ ' ')-1)
SELECT @vc_Name


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -