0

I have a string column where I need to find the substring until the first '-' is found.

Example column ELOT-IGS-2. I need to get "2" as output. These columns come from a table so I cannot declare the variable as a fixed string.

I tried LOCATE, SUBSTRING_INDEX but none are build in functions.

I also tried RIGHT(ID_BETSLIP,CHARINDEX('-',ID_BETSLIP)-1) but this does not work when I have 2 times "-"

Does anyone have an idea?

Igor Borisenko
  • 3,806
  • 3
  • 34
  • 49
Yves Vanlathem
  • 11
  • 1
  • 1
  • 6
  • Check this [LINK](http://stackoverflow.com/questions/16667251/query-to-get-only-numbers-from-a-string) or this [LINK](http://stackoverflow.com/questions/10443462/how-to-get-the-numeric-part-from-a-string-using-t-sql) – Abhi Jun 09 '15 at 06:49
  • Can I declare a varibale that comes from a column in a table? – Yves Vanlathem Jun 09 '15 at 06:55

4 Answers4

4
select RIGHT(<your Field>, CHARINDEX('-',REVERSE(<your Field>))-1)
Ali pishkari
  • 532
  • 4
  • 18
2
DECLARE @t varchar(20) = 'ELOT-IGS-2'
select REVERSE(SUBSTRING(reverse(@t),0,CHARINDEX ('-',REVERSE(@t))))
mohan111
  • 8,633
  • 4
  • 28
  • 55
0
  1. Based on @mohan111's solution you can add REVERSE in order to get what you need

    DECLARE @t varchar(20) = 'ELOT-IGS-2'
    select REVERSE(SUBSTRING(reverse(@t),0,CHARINDEX ('-',REVERSE(@t))))
    

    You should have done this yourself, once you got @mohan111's solution! For your own improvement you can not ask for everything :-( Once you got a solution that is almost what you need, it is time to try to improve it yourself. Please check this MSDN page, and every time that you need to parse a string, START HERE :-) Try to go over the functions and maybe you will find the solution.

  2. The REVERSE query and most string parsing function are not good solution in SQL Server, and in most cases you are better to do this using SQLCLR function.

Michael
  • 8,362
  • 6
  • 61
  • 88
Ronen Ariely
  • 2,336
  • 12
  • 21
0

Simplest would be

select SUBSTRING(reverse(ELOT-IGS-2),0,charindex('-',reverse(ELOT-IGS-2)))
ThePravinDeshmukh
  • 1,823
  • 12
  • 21