Stored Function with Scalar Result

This example shows how to use a stored function that executes some operations and returns a scalar value as a result, for example, like this one:

The script for creating a stored function for the SQL Server DBMS is as follows:

CREATE FUNCTION dbo.Sum(@p1 int, @p2 int)
RETURNS int
AS
BEGIN
        RETURN @p1 + @p2;
END
GO

Create a model and add a new method to it corresponding to the function (either at the stage of creation at the Select database objects page of Create Model Wizard, or by dragging the corresponding stored function from the Database Explorer window to the diagram area or in the Model Explorer window of an already existing model).

As a result, we will get a method in the model corresponding to the stored function:

images_SFwithScalarResultGeneral

With the following parameters:

images_SFwithScalarResultParameters

As a result of code generation for the model, the corresponding method will be generated having a signature close to the relevant stored function:

 

C#:

public static System.Nullable<int> Sum(NHibernate.ISession session, System.Nullable<int> p1, System.Nullable<int> p2)
        {
            NHibernate.IQuery query = session.GetNamedQuery(@"Sum");
            query.SetParameter(@"p1", p1);
            query.SetParameter(@"p2", p2);
            return ((System.Nullable<int>)(query.UniqueResult()));
        }

Visual Basic:

Public Shared Function Sum (session As NHibernate.ISession, p1 As System.Nullable(Of Integer), _
    p2 As System.Nullable(Of Integer)) As System.Nullable(Of Integer)
            Dim query As NHibernate.IQuery = session.GetNamedQuery("Sum")
            query.SetParameter("p1", p1)
            query.SetParameter("p2", p2)
            Return CType(query.UniqueResult(), System.Nullable(Of Integer))
        End Function

Now it is possible to use this stored function in the application with the help of method wrapper. This allows working with the stored function with all possible convenience, as wrapper methods are strongly typed, are found by IntelliSense and have signatures close to the corresponding stored functions.

 

ExpandedToggleIcon        See Also


Send feedback on this topic

© 2008 - 2024 Devart. All rights reserved.