12.2. Creating a Scalar-Valued Function
Problem
You need to create a CLR scalar-valued function.
Solution
The solution creates a scalar-valued function that is a CLR stored procedure that returns the total for a specific sales order by summing the LineTotal
values in the Sales.SalesOrderDetail
table in AdventureWorks
for a specified sales order ID. Follow these steps:
Create a new SQL Server project in Visual Studio and name it
ClrScalarValuedFunction
.Create a user-defined function item in the project. Name the item SumLineTotal.cs.
The C# code in SumLineTotal.cs in the project
ClrScalarValuedFunction
is shown in Example 12-5.Example 12-5. File: SumLineTotal.cs
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)] public static SqlMoney SumLineTotal(int salesOrderID) { using (SqlConnection connection = new SqlConnection("context connection=true")) { connection.Open( ); SqlCommand cmd = new SqlCommand( "SELECT SUM(LineTotal) " + "FROM Sales.SalesOrderDetail " + "WHERE SalesOrderID=" + salesOrderID, connection); return (decimal)cmd.ExecuteScalar( ); } } };
Notice that the function returns data type
SqlMoney
and accepts an argumentsalesOrderID
of data typeint
. The actual return value is decimal, which is compatible with the SQL ServerMoney
data type. The function reads data from SQL Server, so the
Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.