0

I have a result of an Select-Statement with strings in this form:

"123400000000020~forename~surname~P50206.00011" 
"123400000111111~forname1~surname1~P50206.00011"  
....

How I can order by the surnames in SQL? Is their a possibilty to cut the strings @ the 2nd "~"?

Sender
  • 6,660
  • 12
  • 47
  • 66
Lustknylch
  • 21
  • 4

2 Answers2

0

CHARINDEX is your friend here. You're going to need to nest it within itself and run it twice because you want the second instance.

DECLARE @SearchString nvarchar(max)
SET @SearchString = '123400000111111~forname1~surname1~P50206.00011'

DECLARE @Delimiter nvarchar(1)
SET @Delimiter = '~'

/*
SELECT @SearchString AS [Your String]
--the string puked back

SELECT 
    RIGHT
        (
        @SearchString, 
        LEN(@SearchString) - charindex(@Delimiter, @SearchString)
        ) AS [The First Instance]
--first instance of @Delimiter
*/  

SELECT 
    RIGHT
    (
        RIGHT
            (
            @SearchString, 
            LEN(@SearchString) - CHARINDEX(@Delimiter, @SearchString)
            ), 
            LEN
            (
                RIGHT(@SearchString, LEN(@SearchString) - CHARINDEX(@Delimiter, @SearchString))
            ) - 
            CHARINDEX
            (
                @Delimiter, RIGHT(@SearchString, LEN(@SearchString) - CHARINDEX(@Delimiter, @SearchString))
            )
    ) AS [Your Awful Order By]
--what you're after

But for the love of all that is sacred in the world of databases as well as the sake of your own sanity, not to mention performance, do not store data like this!

LDMJoe
  • 1,591
  • 13
  • 17
0

I think this will be help you ;

select substr(somedata, regexp_instr(somedata, '(~)', 1, 2, 1)  ,    regexp_instr(substr(somedata, regexp_instr(somedata, '(~)', 1, 2, 1) ),      '(~)', 1, 1, 1)-2 ) as surname from (
select '123400000000020~forename~surname~P50206.00011' as somedata  from dual
  union
   select '123400000111111~forname1~surname1~P50206.00011' as somedata   from dual
union
select '123400000000020~forename~surname3~' as somedata  from dual
union
select '3~~surname5~P50206.00011' as somedata   from dual
)
order by 1 asc
newuserua_ext
  • 577
  • 6
  • 18