Table-Valued Function

User-defined functions that return a table data type can be powerful alternatives to views. These functions are referred to as table-valued functions. A table-valued user-defined function can be used where table or view expressions are allowed in SQL queries.

This example shows how to use a table-valued function that executes inside itself a parameterized SELECT query to a table and returns table records that satisfy the query condition as the list of corresponding entity objects, e.g. like this one:

 

The script for creating a table-valued function and a table for the SQL Server DBMS is as follows:

CREATE TABLE dbo.Department (
  DeptNo int NOT NULL,
  DName varchar(14),
  Loc varchar(13),
  PRIMARY KEY (DeptNo)
)
GO
CREATE FUNCTION dbo.Fun_DepartmentByLocation(@Loc varchar(13))
RETURNS TABLE
AS
RETURN (
        SELECT * FROM dbo.Department WHERE Loc = @Loc
)
GO

Create a model and add a 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_TableValuedFunctionGeneral

With the following parameters:

images_TableValuedFunctionParameters

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 IList<testmodellermodel.department> FunDepartmentByLocation(NHibernate.ISession session, string Loc)
        {
            NHibernate.IQuery query = session.GetNamedQuery(@"FunDepartmentByLocation");
            query.SetParameter(@"Loc", Loc);
            return query.List<testmodellermodel.department>();
        }

Visual Basic:

Public Shared Function FunDepartmentByLocation ( _
    session As NHibernate.ISession, Loc As String) As List(Of testmodellerModel.Department)
            Dim query As NHibernate.IQuery = session.GetNamedQuery("FunDepartmentByLocation")
            query.SetParameter("Loc", Loc)
            Return query.List(Of testmodellerModel.Department)()
        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.