value extraction

  • I have a varchar value as

    C-P-M-T-U-R

    how can I find out the value between the first two hypens(-) that is in above example it would be P

  • Try the following..

    DECLARE@strString VARCHAR(100)

    DECLARE@strDelimiter VARCHAR(1)

    DECLARE@iPosition1 INT

    DECLARE@iPosition2 INT

    SELECT@strString = 'C-P-M-T-U-R',

    @strDelimiter = '-',

    @iPosition1 = CHARINDEX( @strDelimiter, @strString ),

    @iPosition2 = CHARINDEX( @strDelimiter, @strString, iPosition1 + 1 )

    SELECT SUBSTRING( @strString, @iPosition1 + 1, @iPosition2 - @iPosition1 - 1)


    Kingston Dhasian

    How to post data/code on a forum to get the best help - Jeff Moden
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

  • declare @s-2 as varchar(100),@sxml as xml,@no as int

    set @s-2 ='C-P-M-T-U-R'

    set @sxml = cast('<X>'+replace(@s,'-','</X><X>')+'</X>' as xml)

    set @no =2

    select v

    from

    (

    select d.v.value('.','varchar(50)') as v,Row_number() OVER (order by (select 1)) as rnum

    from @sxml.nodes('X') d(v)

    )t where rnum = @no

    pass the value @no as the order of hyphen u want to fetch

    --Divya

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply