Jeg ville gå med en CLR, noget som dette (dette har fordelen ved at arbejde i SET-baserede operationer, hvorimod de dynamiske sql-alternativer (dvs. Abduls svar) ikke vil):
EDIT: Kildekode til CLR dll'en (Visual Studio 2008) udgivet her:http:/ /www.heavencore.co.uk/filehub/uploaded/EvalFunction.zip
Hvis du foretrækker at kompilere samlingen selv, er her koden:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Runtime.InteropServices
Partial Public Class UserDefinedFunctions
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function EVAL(ByVal InputExpression As SqlString) As SqlDecimal
Return Evaluate(InputExpression)
End Function
Private Shared Function Evaluate(ByVal expression As SqlString) As SqlDecimal
Dim expressionStr As String = expression.ToString()
Dim loDataTable = New DataTable()
Dim loDataColumn = New DataColumn("Eval", GetType(Double), expressionStr)
loDataTable.Columns.Add(loDataColumn)
loDataTable.Rows.Add(0)
Return ParseDecimal(loDataTable.Rows(0)("Eval").ToString(), 0)
End Function
Public Shared Function ParseDecimal(ByVal InputStr As String, Optional ByVal ReturnIfFail As Decimal = 0) As Decimal
Dim ParseOutput As Decimal = 0
If Decimal.TryParse(InputStr, ParseOutput) = False Then
Return ReturnIfFail
Else
Return ParseOutput
End If
End Function
End Class
når den er installeret og bundet, kan du gøre dette:
SELECT Faktor, dbo.Eval(Faktor) as Result FROM Artikel
Rediger:OK, jeg har lige testet dette, og det fungerer fint i sæt-baserede operationer osv., installationen var som følger:
-- Enable the CLR to run user-defined functions
EXEC sp_configure
'clr enabled' ,
'1'
GO
RECONFIGURE
GO
-- Set the appropriate database security permission
ALTER DATABASE [TargetDatabase] SET TRUSTWORTHY ON
GO
-- Import the assembly
CREATE ASSEMBLY EvalFunction
FROM 'C:\bin\EvalFunction.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;
GO
-- Create the Eval function for easy use
CREATE FUNCTION dbo.Eval
(
@Expression NVARCHAR(255)
)
RETURNS DECIMAL(18, 2)
AS EXTERNAL NAME
EvalFunction.[EvalFunction.UserDefinedFunctions].EVAL
GO