Delen via


Procedure: Door de gebruiker gedefinieerde tabelwaardefuncties gebruiken

Een tabelwaardefunctie retourneert één rijenset (in tegenstelling tot opgeslagen procedures, die meerdere resultaatshapes kunnen retourneren). Omdat het retourtype van een tabelwaardefunctie is Table, kunt u een tabelwaardefunctie overal in SQL gebruiken die u kunt gebruiken in een tabel. U kunt de tabelwaardefunctie ook net als een tabel behandelen.

Voorbeeld 1

Met de volgende SQL-functie wordt expliciet aangegeven dat er een TABLE. Daarom wordt de geretourneerde rijsetstructuur impliciet gedefinieerd.

CREATE FUNCTION ProductsCostingMoreThan(@cost money)  
RETURNS TABLE  
AS  
RETURN  
    SELECT ProductID, UnitPrice  
    FROM Products  
    WHERE UnitPrice > @cost  

LINQ aan SQL wijst de functie als volgt toe:

[Function(Name="dbo.ProductsCostingMoreThan", IsComposable=true)]
public IQueryable<ProductsCostingMoreThanResult> ProductsCostingMoreThan([Parameter(DbType="Money")] System.Nullable<decimal> cost)
{
    return this.CreateMethodCallQuery<ProductsCostingMoreThanResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), cost);
}
   <FunctionAttribute(Name:="dbo.ProductsCostingMoreThan", IsComposable:=True)> _
Public Function ProductsCostingMoreThan(<Parameter(DbType:="Money")> ByVal cost As System.Nullable(Of Decimal)) As IQueryable(Of ProductsCostingMoreThanResult)
       Return Me.CreateMethodCallQuery(Of ProductsCostingMoreThanResult)(Me, CType(MethodInfo.GetCurrentMethod, MethodInfo), cost)
   End Function

Voorbeeld 2

In de volgende SQL-code ziet u dat u kunt samenvoegen met de tabel die door de functie wordt geretourneerd en anders kunt behandelen als elke andere tabel:

SELECT p2.ProductName, p1.UnitPrice  
FROM dbo.ProductsCostingMoreThan(80.50)  
AS p1 INNER JOIN Products AS p2 ON p1.ProductID = p2.ProductID  

In LINQ naar SQL wordt de query als volgt weergegeven:

        var q =
from p in db.ProductsCostingMoreThan(80.50m)
join s in db.Products on p.ProductID equals s.ProductID
select new { p.ProductID, s.UnitPrice };
    Dim q = _
From p In db.ProductsCostingMoreThan(80.5), p1 In db.Products _
Where p.ProductID = p1.ProductID _
Select p.ProductID, p1.UnitPrice

Zie ook