用于将字符串表达式转换为适当值的SQL函数 [英] SQL function for converting string expression to proper value

查看:125
本文介绍了用于将字符串表达式转换为适当值的SQL函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数将数学表达式转换为浮点值:

  create function dbo.ExpressionToValue 

@expression nvarchar(最大)

返回float作为
begin
declare @result float
- 转换代码
return @result
end

预期用法:

  select dbo.ExpressionToValue('2 + 3')

预期结果:

  5 

$ b

解决方案

另一种黑客就是利用C#作为程序集的形式。



您可以创建一个汇编函数,如

 使用System.Data.DataTable 
使用System.Data.SqlTypes;
使用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));


}
}

构建程序集使用VisualStudio然后
注册程序集。需要注意的一点是,您可能需要编译到.NET框架的较低版本,具体取决于当前版本的SQL Server支持哪一个。



您可以使用MSDN上描述的过程在SQL Server中注册程序集 https://msdn.microsoft.com/en-us/library/w2kae45k(v = vs.100).aspx


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

解决方案

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

这篇关于用于将字符串表达式转换为适当值的SQL函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆