我喜欢用不同的公式填充我的数据库。
当我在数据库中有一个公式时,例如"(2+4)*5"
我得到的结果40
:
update DB.dbo.INFOGROUP SET formula = '(2+4)*5' where INFOGROUP = 'S42'
当我在数据库中有一个公式时,例如"(x+4)*5"
我得到的结果20
.即使我将x
的值设置为10
,也会忽略x
值:
update DB.dbo.INFOGROUP SET formula = '(x+4)*5' where INFOGROUP = 'S42'
Private Sub BtnCalculate_Click(sender As Object, e As EventArgs) Handles BtnCalculate.Click
Dim SC As New MSScriptControl.ScriptControl
Dim x As Double = 10
SQL.AddParam("@infogroup", "S42")
SQL.ExecQuery($"SELECT formula FROM DB.dbo.INFOGROEP where infogroep=@infogroep")
Dim Formula As String = <string_from_db>
'SET LANGUAGE TO VBSCRIPT
SC.Language = "VBSCRIPT"
'ATTEMPT MATH
Try
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))
'SHOW THAT IT WAS VALID
MessageBox.Show("Math success, " & Formula & " equals " & Result.ToString)
Catch ex As Exception
'SHOW THAT IT WAS INVALID
MessageBox.Show("Not a valid math formula for a double.")
End Try
End Sub
这是否可能,或者我是否需要第三方脚本?
顺便说一句:在Visual Foxpro中有一个类似于EVAL(db_string)
的功能。
脚本引擎不了解方法中的变量。 如果要计算包含变量的公式,则需要告诉它该变量具有什么值:
SC.Language = "VBSCRIPT"
sc.AddCode "Private Const x = 10"
Dim Result As Double = Convert.ToDouble(SC.Eval(Formula))