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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 substring/charindex help

Author  Topic 

Brittney10
Posting Yak Master

154 Posts

Posted - 2012-09-04 : 13:13:56
I need to get all the numbers to the left of the "-" (hyphen)
for example, I have "1234-5678" and I need to get "1234" from that string. The length of the string to the left of the hypen is not the same on all records. Thanks for the help in advance.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-04 : 13:21:20
quote:
Originally posted by Brittney10

I need to get all the numbers to the left of the "-" (hyphen)
for example, I have "1234-5678" and I need to get "1234" from that string. The length of the string to the left of the hypen is not the same on all records. Thanks for the help in advance.

You can use the LEFT function like this:
SELECT LEFT(YourCol,CHARINDEX('-',YourCol)-1);
This will fail if you have any row that does not have a hyphen in it.
Go to Top of Page

vijayan.vinu3
Starting Member

19 Posts

Posted - 2012-09-05 : 05:19:01
This is another method of doing it:


Declare @string Varchar(30) = '1234-5678'
Select SubString(@String, 0,PATINDEX('%[^0-9]%', @string)) As String
Go to Top of Page
   

- Advertisement -