• StringBuilder is a great example. So is pretty much any math operation. Recently, I've been playing with the following method, which mathematically reverses an integer:

    -----------------------------------------------------------

    [SqlFunction]

    public static int ReverseNumber (int number)

    {

    int reverse = 0;

    do

    {

    reverse = (reverse * 10) + (number % 10);

    number = number / 10;

    }

    while (number > 0);

    return (reverse);

    }

    -----------------------------------------------------------

    Here is the equivalent in a T-SQL UDF:

    -----------------------------------------------------------

    CREATE FUNCTION dbo.NumberReverse

    (

    @InputNum INT

    )

    RETURNS INT

    AS

    BEGIN

    DECLARE @Reverse INT

    SET @Reverse = @InputNum % 10

    SET @InputNum = @InputNum / 10

    WHILE @InputNum > 0

    BEGIN

    SET @Reverse = (@Reverse * 10) + (@InputNum % 10)

    SET @InputNum = @InputNum / 10

    END

    RETURN (@Reverse)

    END

    GO

    -----------------------------------------------------------

    Run both of these 10000 or 100000 times on your system, using a script such as the following:

    DECLARE @i INT

    SET @i = 1

    DECLARE @j-2 INT

    SET @j-2 = 1234567

    WHILE @i < 10000

    BEGIN

    SET @j-2 = dbo.NumberReverse(@j)

    SET @i = @i + 1

    END

    ... On my test system, the CLR version runs twice as fast. I'd be interested in hearing others' results.

    --
    Adam Machanic
    whoisactive