.NET Framework の共通言語ランタイム (CLR) では、属性と呼ばれる説明キーワードを使用できます。 これらの属性は、メソッドやクラスなど、多くの要素に追加情報を提供します。 属性はオブジェクトのメタデータと共にアセンブリに保存され、コードを他の開発ツールに記述したり、SQL Server 内のランタイム動作に影響を与えたりするために使用できます。
CLR ルーチンを SQL Server に登録すると、SQL Server によってルーチンに関する一連のプロパティが派生します。 これらのルーチン プロパティは、ルーチンの機能 (ルーチンにインデックスを付けることができるかどうかなど) を決定します。 たとえば、 DataAccess
プロパティを DataAccessKind.Read
に設定すると、CLR 関数内の SQL Server ユーザー テーブルのデータにアクセスできます。 次の例は、ユーザー テーブル table1 からのデータ アクセスを容易にするために DataAccess
プロパティが設定されている単純なケースを示しています。
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Data.SqlClient;
public partial class UserDefinedFunctions
{
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static string func1()
{
// Open a connection and create a command
SqlConnection conn = new SqlConnection("context connection = true");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT str_val FROM table1 WHERE int_val = 10";
// where table1 is a user table
// Execute this command
SqlDataReader rd = cmd.ExecuteReader();
// Set string ret_val to str_val returned from the query
string ret_val = rd.GetValue(0).ToString();
rd.Close();
return ret_val;
}
}
Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlClient
Public partial Class UserDefinedFunctions
<SqlFunction(DataAccess = DataAccessKind.Read)> _
Public Shared Function func1() As String
' Open a connection and create a command
Dim conn As SqlConnection = New SqlConnection("context connection = true")
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SELECT str_val FROM table1 WHERE int_val = 10"
' where table1 is a user table
' Execute this command
Dim rd As SqlDataReader = cmd.ExecuteReader()
' Set string ret_val to str_val returned from the query
Dim ret_val As String = rd.GetValue(0).ToString()
rd.Close()
Return ret_val
End Function
End Class
Transact-SQL ルーチンの場合、SQL Server はルーチン定義からルーチン プロパティを直接派生させます。 CLR ルーチンの場合、サーバーはルーチンの本体を分析してこれらのプロパティを派生しません。 代わりに、.NET Framework 言語で実装されているクラスとクラス メンバーにカスタム属性を使用できます。
CLR ルーチン、ユーザー定義型、集計に必要なカスタム属性は、 Microsoft.SqlServer.Server
名前空間で定義されます。