Q:

TSQL Algebra - solve for x ((a)x < b)

I have a table consiting of about 940 rows.  I am creating a specialised calculation that needs to solve the following:
For each row, how many times can I multiply A without it going above B.
I created a UDF to do this as follows:
DECLARE @x int;
DECLARE @Result decimal(18,4);
DECLARE @CutOff int;

SELECT @x=0, @CutOff=1000, @Result=null;

WHILE (((@Result < @tVal) or (@Result IS NULL)) AND @x < @CutOff) BEGIN 
    SET @x = @x + 1;
    SET @Result = @hProb * @x;
END

IF (@x = @CutOff)
    SET @x = -1;

RETURN @x;

@tVal is the target value we are look to achieve.
@CutOff is a maximum number to multiply by, if x reaches this number and still has not gone above the target value then stop the loop and return a negative number

This works but where my SP usually takes about 20 seconds to run, when I add this function it adds about 6.5 minutes to the processing time.
If possible I'd like a more efficient way to do this but I can't find a better solution so far.
All help is appreciated.

A:

select case
    when @hProb * @Cutoff <= @tVal then -1
    else floor(@tVal / @hProb)
end;

And it might have side effects, depending on the actual data types of your arguments.

