While PatIndex

  • Help please,

    I have this code that uses patindex and I want to loop through it to do a replace.

    Declare @idx_Operator nvarchar(10)

    Declare @Operator nvarchar(10)

    Declare @formula nvarchar(100)

    select @formula = 'BRIDGESTONE+FIRESTONE perelli-MyTire'--formula from goal_formulas where id = 1

    while PATINDEX('%[+-/*|]%', @formula) > 0

    begin

    SELECT @idx_Operator=PATINDEX('%[+-/*|]%', @formula)

    ,@Operator=LTrim(RTrim(substring(@formula,patindex('%[+-/*|]%',@formula),1)))

    set @formula = replace(@formula, @Operator, ' ')

    end

    select @idx_Operator as idx_Operator, @Operator as operator,@formula

    If you run the following you just get back BRIDGESTONE+FIRESTONE perelli-MyTire

    It didn't seem to get the + and -?

  • I think your problem is the patindex. The expression is not right... Always use SELECT first to make sure you are getting from your PATINDEX what you think you are.

    Jared
    CE - Microsoft

  • Actually... start with this:

    Declare @idx_Operator nvarchar(10)

    Declare @Operator nvarchar(10)

    Declare @formula nvarchar(100)

    select @formula = 'BRIDGESTONE+FIRESTONE perelli-MyTire'--formula from goal_formulas where id = 1

    SELECT PATINDEX('%[+-/*|]%', @formula)

    SELECT PATINDEX('%[+%-%/%*%|]%', @formula)

    See?

    Jared
    CE - Microsoft

  • Gotcha Thanks Keith.

  • No problem, but I am certainly not an expert (or even the least bit knowledgeable) on REGEXs. Should look at this a bit more.

    Jared
    CE - Microsoft

  • Hmm... That won't work either. Take out the + from the string and leave in the -, then the result of the patindex returns 0 again. Hmm...

    Jared
    CE - Microsoft

  • This fixes the patindex, can't start it with a - in the regex. However, your query only displays the last character replaced. Is that what you want?

    Declare @idx_Operator nvarchar(10)

    Declare @Operator nvarchar(10)

    Declare @formula nvarchar(100)

    select @formula = 'BRIDGESTONE+FIRESTONE perelli-MyTire'--formula from goal_formulas where id = 1

    while PATINDEX('%[-+*/|]%', @formula) > 0

    begin

    SELECT @idx_Operator=PATINDEX('%[-+*/|]%', @formula)

    ,@Operator=LTrim(RTrim(substring(@formula,patindex('%[-+*/|]%',@formula),1)))

    set @formula = replace(@formula, @Operator, ' ')

    end

    select @idx_Operator as idx_Operator, @Operator as operator,@formula

    Jared
    CE - Microsoft

  • That's it. Thanks alot.

Viewing 8 posts - 1 through 7 (of 7 total)

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