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
ClrScalarValuedFunctionis 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
SqlMoneyand accepts an argumentsalesOrderIDof data typeint. The actual return value is decimal, which is compatible with the SQL ServerMoneydata type. The function reads data from SQL Server, so the
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access