In my earlier article, I wrote about a new major enhancement in LOG function in SQL Server 2012 and the enhancement is that you can pass any custom base value along with the expression to calculate the natural logarithm in this function. Recently, I received a query from Mr. Willy Van inquiring how to custom the base value in the LOG function in the earlier versions of SQL Server. After some research I finally developed a solution that can help you to pass custom base value along with the expression in the earlier versions of SQL Server.
Given below is user defined function that calculate the LOG with custom base value.
SOLUTION :
--DROP FUNCTION [dbo].[LOG] --GO CREATE FUNCTION [dbo].[LOG](@Number float,@Base bigint) RETURNS float AS Begin DECLARE @Log float SET @Log = (log10(@Number)*2.302585093)/(log10(@Base)*2.302585093) RETURN @Log End GOEXAMPLE :
SELECT 1 as [Number] , 10 as Base, dbo.[LOG](1,10) As [Log] UNION ALL SELECT 2 as [Number] , 15 as Base, dbo.[LOG](2,15) As [Log] UNION ALL SELECT 3 as [Number] , 30 as Base, dbo.[LOG](3,30) As [Log] UNION ALL SELECT 4 as [Number] , 45 as Base, dbo.[LOG](4,45) As [Log] --OUTPUT GOReference : MSDN
Leave a Reply