• If you wanted too, you can make this follow the order of operations (except for parentheses) with a few small changes.

    Where you currently have it decide which the last operator is by separately comparing each of the four operators, instead have it always pick addition and subtraction first, then the others. Your existing code to go from left to right will handle the rest.

    --figure out which operation is last

    if @addIdx > @firstIdx

    begin

    set @firstIdx = @addIdx

    set @precedent = 1

    end

    if @subIdx > @firstIdx

    begin

    set @firstIdx = @subIdx

    set @precedent = 1

    end

    --Add restriction that addition/subtraction must be found first (and so done last)

    if @multIdx > @firstIdx AND @precedent = 0

    begin

    set @firstIdx = @multIdx

    end

    if @divIdx > @firstIdx AND @precedent = 0

    begin

    set @firstIdx = @divIdx

    end

    if @modIdx > @firstIdx AND @precedent = 0

    begin

    set @firstIdx = @modidx

    end

    Then in each of your cases, be sure to run the function on both halves

    select @nopr2 = dbo.fn_simplemath(@opr2)

    select @nopr1 = dbo.fn_simplemath(@opr1)