Parsing a string before the last character index in SQL Server

I started with this, but is this the best way to complete the task?

select  
    reverse(
        substring(reverse(some_field),
        charindex('-', reverse(some_field)) + 1, 
        len(some_field) - charindex('-', reverse(some_field)))) 
from SomeTable
  • How does SQL Server handle multiple calls reverse(some_field)?
  • Besides UDF and iterating through a string looking for a charindex β€œ-” and storing the last of its index, is there still an efficient way to accomplish this task in T-SQL?

Please note that I have work, I'm just wondering if this is the best way.

Below are some sample values ​​for some_field.

s2-st, s1-st, s3-st, s3-sss-zzz, s4-sss-zzzz

EDIT:

An example output for this would be ...

s1, s2, s3-sss, s3, s4-sss

The solution written by ErikE actually gets the end of the line, so everything after the last hyphen. I just changed its version to get everything before using a similar method with a function instead left. Thank you for your help.

select left(some_field, abs(charindex('-', reverse(some_field)) - len(some_field)))
    from (select 's2-st' as some_field
        union select 's1-st'
        union select 's3-st'
        union select 's3-sss-zzz'
        union select 's4-sss-zzzz') as SomeTable
+3
4

:

select right(some_field, charindex('-', reverse(some_field)) - 1)
from SomeTable

, , , 8000 , . varchar (max), .

, , , # 1, , # 2 , /, .

, , SQL Server (some_field) . - , .

, - , . . , , :

select left(some_field, len(some_field) - charindex('-', reverse(some_field)))
from (
   select 's2-st'
   union all select 's1-st'
   union all select 's3-st'
   union all select 's3-sss-zzz'
   union all select 's4-sss-zzzz'
   union all select 's5'
) X (some_field)

() . + len - charindex + charindex - len, . .

: UNION SELECT UNION ALL SELECT, ALL , SELECT DISTINCT. ALL, .:)

+5

# 1, , . , ?

- - .

0

, SQL Server REVERSE CHARINDEX.

CHARINDEX, :

select  
    reverse(
        substring(reverse(some_field),
        charindex('-', reverse(some_field)) + 1, 
        len(some_field))) 
from SomeTable

, LEN :

select  
    reverse(
        substring(reverse(some_field),
        charindex('-', reverse(some_field)) + 1, 
        1024)) 
from SomeTable

, .

0
  • 3 . , .

  • ErikE TSQL. LEN

0

Source: https://habr.com/ru/post/1765203/


All Articles