3

I have a table which has a column 'Faktor' (varchar(50)) which contains expressions like:

1/3
2*9/5
0.567
0.23

No, I am searching a way to execute a select like

select Faktor from Artikel

which should return a column of type decimal with the values

0.333333
3.6
0.567
0.23

3 Answers 3

4

I'd go with a CLR, something like this (this has the advantage of working in SET based operations whereas the dynamic sql alternatives (i.e. Abduls answer) will not):

EDIT: Source Code for the CLR dll (Visual Studio 2008) posted here: http://www.heavencore.co.uk/filehub/uploaded/EvalFunction.zip

If you would prefer to compile the assembly yourself, here is the code:

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

once installed and bound you could then do this:

SELECT Faktor, dbo.Eval(Faktor) as Result FROM Artikel

Edit: OK, i have just tested this and it works fine in set-based operations etc, installation was as follows:

-- 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
4
  • Many thanks for your sample. I have done all your steps successfully. But when I try to execute the SQL-Select, I get the fallowing Exception: System.IO.FileLoadException: Die Datei oder Assembly "pp.sqlserver.library, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" oder eine Abhängigkeit davon wurde nicht gefunden. Der angegebene Assemblyname oder die Codebasis ist ungültig. (Ausnahme von HRESULT: 0x80131047) System.IO.FileLoadException
    – BennoDual
    Commented Apr 23, 2012 at 12:04
  • My German isnt great but it sounds like the assembly cant be found? are you sure you installed it the the correct database?
    – HeavenCore
    Commented Apr 23, 2012 at 12:08
  • Yes - I have used your query - I have added 'use [PPSystem_DOS]' at the beginning. The Assembly is listed in the correct database when I look with Management Studio. I ask me, why it does not show the Version-Information in the Exception (instead of 0.0.0.0) - my assembly has a version.
    – BennoDual
    Commented Apr 23, 2012 at 12:54
  • just out of curiosity, what happens if you use my pre-compiled DLL and install it as EvalFunction.[EvalFunction.UserDefinedFunctions].EVAL instead of PPSystem_DOS - does that give the same error?
    – HeavenCore
    Commented Apr 23, 2012 at 12:59
2

too bad. In the expression all numbers are int datatype. So, its difficult to calculate and show the result in decimal.

Here is a sample, hope it will help-

declare @expr nvarchar(10)
set @expr='2*9/5'
declare @query varchar(800)

BEGIN TRY
    SELECT CAST(@expr as decimal(5,2))
END TRY
BEGIN CATCH
    SET @query='SELECT CAST('+@expr+'.0 as decimal(5,2))'
    EXECUTE(@query)
END CATCH
0

You could use the execute statment to compile the string to the result of the represented expression or you evaluate the expression in your application.

1
  • Can you give me a sample how to do this?
    – BennoDual
    Commented Apr 23, 2012 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.