SQL - 在特定符号后排序

时间:2016-01-13 13:56:51

标签: sql

我有一个Select-Statement的结果,其中包含以下形式的字符串:

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

我如何通过SQL中的姓氏订购?他们是否有可能切断第二个"〜"?

的字符串

2 个答案:

答案 0 :(得分:0)

CHARINDEX是你的朋友。您需要将其嵌套在自身中并运行两次,因为您需要第二个实例。

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

但是对于数据库世界中所有神圣的爱以及你自己的理智,更不用说表现,不要存储这样的数据!

答案 1 :(得分:0)

我认为这会对你有所帮助;

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