获取两个字符SQL Server 2008R2之间的字符串

时间:2017-11-17 19:35:12

标签: sql-server string split sql-server-2008-r2

如何从下面的字符串中选择 abc1234

20250-abcdef-abc1234-0123

注意*字符串大小各不相同。

1 个答案:

答案 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