SQL Server Get all the text after the dash: - [closed]

ldioqlga  于 2023-04-28  发布在  其他
关注(0)|答案(2)|浏览(133)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 4 hours ago.
The community is reviewing whether to reopen this question as of 3 hours ago.
Improve this question

I need to extract the second part from text after the dash-

For example, Segment_Name needs to become Segment

SELECT 
    s.segment_name,
    LTRIM(SUBSTRING(s.segment_name, LEN(s.segment_name) - 7, LEN(s.segment_name))) AS Segment
FROM 
    [prod_idw_mart].[t].[dim_segment] s

This works as such except that the -7 is too short. Strangely enough that works in SAS perfectly. But in SQL, the second part of the words are cut short.

There is no specific length I can assign, so I was looking for another solution.

SELECT 
    s.segment_name,
    RIGHT(s.segment_name, CHARINDEX('-', REVERSE(s.segment_name)) - 1) AS S
FROM 
    [prod_idw_mart].[timesheet].[dim_segment] s

Here I get an error:

Invalid length parameter passed to the RIGHT function.

Instead of -1, I tried > 0, but it does not like that at all:

Incorrect syntax near '>'.

px9o7tmv

px9o7tmv1#

declare @delms varchar(20)='%[-,:]%';

select 
     segment_name
    ,case when PATINDEX(@delms, segment_name)=0 
        then '' 
        else substring(segment_name, 1+PATINDEX(@delms, segment_name), len(segment_name)) 
    end as segment
from @table_name
yyyllmsg

yyyllmsg2#

Try the following:

select Segment_Name,
  trim
  (
    right
    (
      translate(Segment_Name, ',:','--'),
      len(Segment_Name) - iif(charindex('-', translate(Segment_Name, ',:','--'))>0, 
                              charindex('-', translate(Segment_Name, ',:','--')), 
                              len(Segment_Name)
                             )
    )
  ) as Segment
from table_name

Demo

Note:

This supposes only one delimiter in the string. For the translate function, you may add extra delimiters to the ',:' list, and if your version of SQL Server doesn't support this function you may use multiple replace functions instead.

相关问题