

--Factorial

--sql code
CREATE FUNCTION FactSQL (@x FLOAT)
-- Compute the factorial of x
RETURNS FLOAT
AS
BEGIN
	DECLARE @y FLOAT
	SET @y = 1.0
	WHILE (@x > 1)
	BEGIN
		SET @y = @x * @y
		SET @x = @x - 1
	END
	RETURN @y
END
GO

 
//clr code
public static double FactClr(double x) {
    double y;
    y = 1.0;
    while(x > 1.0) {
      y = y * x;
      x = x - 1;
  }
    return y;

}


--use northwind to calculate the factorial
--over to columns and check the timings

DECLARE @a DATETIME, @b DATETIME
SET @a = GETDATE()
 
SELECT dbo.factclr(quantity), dbo.factclr(productid) from [Order Details]
SELECT dbo.factsql(quantity), dbo.factsql(productid) from [Order Details]
 
SET @b = GETDATE()
 
-- Show how many milliseconds the query took to execute
SELECT DATEPART(ms, @b-@a)