SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Substring from a Name feild
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

jim_jim
Constraint Violating Yak Guru

USA
306 Posts

Posted - 09/24/2013 :  13:45:21  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3742 Posts

Posted - 09/24/2013 :  15:19:15  Show Profile  Reply with Quote
LEFT(YourNameColumn,CHARINDEX(' ',YourNameColumn+' '))
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

Belarus
172 Posts

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


substring(value, 1, len(value) - 2)

Edited by - sigmas on 09/24/2013 17:13:20
Go to Top of Page

mohan123
Constraint Violating Yak Guru

India
252 Posts

Posted - 09/25/2013 :  01:32:13  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 09/25/2013 :  07:56:52  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000