I need to write a TSQL user defined function which will accept a string and return a number.
I will call the function like dbo.EvaluateExpression(\'10*4.5*0.5\
Use this Function, It will absolutely working.
CREATE FUNCTION dbo.EvaluateExpression(@list nvarchar(MAX))
RETURNS Decimal(10,2)
AS
BEGIN
Declare @Result Decimal(10,2)
set @Result=1
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex('*', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
Set @Result=@Result*convert(decimal(10,2),substring(@list, @pos + 1, @valuelen))
SELECT @pos = @nextpos
END
RETURN @Result
END
You Can use this
Select 10* dbo.EvaluateExpression('10*4.5*0.5')