SQL function for converting string expression to proper value

非 Y 不嫁゛ 提交于 2020-01-07 10:00:21

问题


I need a function to convert mathematical expressions to a float value:

create function dbo.ExpressionToValue
(
     @expression nvarchar(max)
)
returns float as 
begin
     declare @result float 
     --convertion codes 
     return @result
end 

expected usage:

select dbo.ExpressionToValue('2+3')

expected result:

5

回答1:


An alternative hack is to leverage C# in the form of an assembly. C# does not have an eval function, but this too can be hacked.

You can create an assembly function like

using System.Data.DataTable
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{


    [SqlFunction()]
    public static double eval(string expression)
    {

      System.Data.DataTable table = new System.Data.DataTable();
      return Convert.ToDouble(table.Compute(expression, String.Empty)); 


    }
}

Build the assembly using VisualStudio and then register the assembly. One word of caution is that you might have to compile down to a lower version of the .NET framework depending on which one is supported by your current version of SQL server.

You can register your assembly in SQL Server using the procedure described on MSDN https://msdn.microsoft.com/en-us/library/w2kae45k(v=vs.100).aspx



来源:https://stackoverflow.com/questions/40984068/sql-function-for-converting-string-expression-to-proper-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!