String Expression to be evaluated to number

前端 未结 4 1620
感情败类
感情败类 2020-12-07 01:58

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\

4条回答
  •  渐次进展
    2020-12-07 02:17

    Disclaimer: I'm the owner of the project Eval SQL.NET

    For SQL 2012+, you can use Eval SQL.NET which can be run with SAFE Permission.

    The performance is great (better than UDF) and honors operator precedence and parenthesis. In fact, almost all the C# language is supported.

    You can also specify parameters to your formula.

    -- SELECT 225.00
    SELECT 10 * CAST(SQLNET::New('10*4.5*0.5').Eval() AS DECIMAL(18, 2))
    
    -- SELECT 70
    DECLARE @formula VARCHAR(50) = 'a+b*c'
    SELECT  10 * SQLNET::New(@formula)
                        .Val('a', 1)
                        .Val('b', 2)
                        .Val('c', 3)
                        .EvalInt()
    

提交回复
热议问题