38

I'd like to select everything AFTER a certain character (-) that is placed on the most right side.

Eg.

abcd-efgh-XXXX

And I'd like to select the XXXX part

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
coblenski
  • 1,119
  • 2
  • 11
  • 19

8 Answers8

92

You can use:

select right(col, charindex('-', reverse(col)) - 1)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • 10
    Thank you for just answering the question, and not questioning or querying the intentions of the question asker. – shawty May 19 '21 at 11:10
5
DECLARE @x varchar(100)
SET @x = 'abcd-efgh-XXXX'
SELECT RIGHT(@x, CHARINDEX('-', REVERSE(@x)) - 1)
ADyson
  • 57,178
  • 14
  • 51
  • 63
2

Using string split available from SQLServer 2016

;with cte
as
(
 select 
*,row_number() over (order by (select null)) as rownum
 from string_split('abcd-efgh-XXXX','-')
)
select top 1 * from cte 
order by rownum desc
TheGameiswar
  • 27,855
  • 8
  • 56
  • 94
  • This was a good concept. I'm on SQL 2014, so I don't have string_Split available, but I do have a user defined split function, that did the trick. Thanks for the nudge in the right direction! – KirstieBallance May 02 '18 at 19:00
1

@thegameiswar had a clever solution, since I needed the results from a comma delimited list. I don't have SQL 2016, so I made it work with a user defined split function.

;with cte
as
(
 select 
 *,row_number() over (order by (select null)) as rownum
 from database..[fn_SplitDelimitedList](@CommaDelimitedList,',')
)
select * from cte 
order by rownum desc
KirstieBallance
  • 1,238
  • 12
  • 26
0
select substr('Prueba,Prueba2',instr('Prueba,Prueba2',',') + 1) from dual
4b0
  • 21,981
  • 30
  • 95
  • 142
0

SQL Server Management Studio v15.0.18206.0 (18.4):

RIGHT([col], CHARINDEX('-', REVERSE([col]), -1))

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
  • 1
    Hey meraxes! Welcome to stack overflow. You might want enclose your sql query in a code block. – ali Nov 20 '19 at 08:52
0

This is how to do the opposite of this question. i.e everything before the certain character that's placed on the right most side. If anyone found this question looking for the opposite like I did...

DECLARE @x varchar(100)
SET @x = 'abcd-efgh-XXXX'
SELECT LEFT(@x,LEN(@x) - CHARINDEX('-', REVERSE(@x)))

Then you would get abcd-efgh

ocean800
  • 3,489
  • 13
  • 41
  • 73
-1

Worked for me in the case you are using postgres:

SELECT RIGHT(col, POSITION('-' IN REVERSE(col))-1)

Swap out POSITION for CHARINDEX

Max Wulff
  • 1
  • 2