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
 Getting rid of everything after underscore
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Johnph
Yak Posting Veteran

95 Posts

Posted - 09/11/2013 :  09:41:12  Show Profile  Reply with Quote
Hello,

I have data that looks like this:

CAT_DOG
MICE_CAT
RABBIT_DOG
LION_MICE

I want a select clause that will give me just this:

CAT
MICE
RABBIT
LION

Lumbago
Norsk Yak Master

Norway
3271 Posts

Posted - 09/11/2013 :  09:45:24  Show Profile  Reply with Quote
SELECT LEFT(columnname, charindex('_', columnname)-1)

- Lumbago
My blog-> http://thefirstsql.com
Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3661 Posts

Posted - 09/11/2013 :  09:57:18  Show Profile  Reply with Quote
And, in case you could have rows in which there is no underscore,
SELECT LEFT(columnname, charindex('_', columnname+'_')-1)
Go to Top of Page

Lumbago
Norsk Yak Master

Norway
3271 Posts

Posted - 09/11/2013 :  10:02:11  Show Profile  Reply with Quote
quote:

And, in case you could have rows in which there is no underscore,
SELECT LEFT(columnname, charindex('_', columnname+'_')-1)


My bad

- Lumbago
My blog-> http://thefirstsql.com
Go to Top of Page

Johnph
Yak Posting Veteran

95 Posts

Posted - 09/11/2013 :  12:00:13  Show Profile  Reply with Quote
Thank you!
Go to Top of Page

mohan123
Constraint Violating Yak Guru

India
252 Posts

Posted - 09/16/2013 :  09:55:10  Show Profile  Reply with Quote
Hi John,

Another Way
DECLARE @v_ID VARCHAR(20)
SET @v_ID = 'CAT_DOG'

SELECT SUBSTRING(@v_ID,1,CHARINDEX('_',@v_ID+'_')-1)

P.V.P.MOhan
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.05 seconds. Powered By: Snitz Forums 2000