How to get only the last string before comma

  • Hi All,

    I have a string like below

    DWDate,Email,UserID,ID,LoanNum,PersonEmail,LoanDate,Paymt

    I want to get the last one that is Paymt. Actually the upper section is generated from a variable. there may be other values we can get but I want only the last one beofre comma (,).

    From the string DWDate,Email,UserID,ID,LoanNum,PersonEmail,LoanDate,Paymt I want only "Paymt"

    Can you please help me?

  • You want the string after the last comma?

    The one before the last comma would be LoanDate

    DECLARE @STR VARCHAR(250) = 'DWDate,Email,UserID,ID,LoanNum,PersonEmail,LoanDate,Paymt'

    SELECT REVERSE(LEFT(REVERSE(@str), CHARINDEX(',', REVERSE(@str))-1))

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • Hi GilaMonster,

    You are terrific. It works like a charm!!

    Thanks you so much

  • How about reducing some steps?

    DECLARE @STR VARCHAR(250) = 'DWDate,Email,UserID,ID,LoanNum,PersonEmail,LoanDate,Paymt'

    SELECT RIGHT(@str, CHARINDEX(',', REVERSE(@str))-1)

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2

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

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