问题
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