Substring from string

  • Hello,
    I'm trying to get a substring (in this case  R8241112T) from a string (@var) first by returning the position of a substring. I'm trying to use charindex and patindex. Below is the query:

    DECLARE @var VARCHAR(100) = 'Cosmetic bag 62x190 - Aton Cream R8241112T str98'

    SELECT @var,
    CHARINDEX(@var,'R[0-9]%[ABCEGHUT]',1),
    PATINDEX('R[0-9]%[ABCEGHUT]',@var)

    Unfortunatelly, my attempts return 0, can anyone please help me to achive my goal?
    Best regards

  • Hi,

    Can you please try like:

    DECLARE @var VARCHAR(100) = 'Cosmetic bag 62x190 - Aton Cream R8241112T str98'

    SELECT @var,
    PATINDEX('%R[0-9]%[ABCEGHUT]%',@var),
    SUBSTRING(@var,PATINDEX('%R[0-9]%[ABCEGHUT]%',@var), LEN(SUBSTRING(@var,PATINDEX('%R[0-9]%[ABCEGHUT]%', @var),LEN(@var)))-PATINDEX('% %',REVERSE(@var)))

  • That works like a charm. Thank you very much.
    Best regards

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

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