如何从下面的字符串中选择 abc1234 ?
20250-abcdef-abc1234-0123
注意*字符串大小各不相同。
答案 0 :(得分:2)
declare @var varchar(256) = '20250-abcdef-abc1234-0123'
select right(left(@var,len(@var) - charindex('-',reverse(@var))),charindex('-',reverse(left(@var,len(@var) - charindex('-',reverse(@var))))) - 1)
详细版本
declare @var varchar(256) = '20250-abcdef-abc1234-0123'
declare @FirstHyphenFromRight int
declare @TrimedToFirstHyphen varchar(256)
declare @SecondHyphenFromRight int
declare @Result varchar(256)
select
@FirstHyphenFromRight = charindex('-',reverse(@var))
,@TrimedToFirstHyphen = left(@var,len(@var) - @FirstHyphenFromRight)
,@SecondHyphenFromRight = charindex('-',reverse(@TrimedToFirstHyphen))
,@Result = right(@TrimedToFirstHyphen, @SecondHyphenFromRight - 1) --minus 1 for the hyphen
select
YourString = @var
,FirstHyphenFromRight = @FirstHyphenFromRight
,TrimedToFirstHyphen = @TrimedToFirstHyphen
,SecondHyphenFromRight = @SecondHyphenFromRight
,Result = @Result