次の方法で共有


キャプチャ モードの使用

SMO プログラムは、プログラムによって実行されるステートメントの代替または追加として、プログラムによって発行される同等の Transact-SQL ステートメントのキャプチャおよび記録を行うことができます。キャプチャ モードを有効にするには、ServerConnection オブジェクトを使用するか、Server オブジェクトの ConnectionContext プロパティを使用します。

提供されているコード例を使用するには、アプリケーションを作成するプログラミング環境、プログラミング テンプレート、およびプログラミング言語を選択する必要があります。詳細については、SQL Server オンライン ブックの「Visual Studio .NET で Visual Basic SMO プロジェクトを作成する方法」および「Visual Studio .NET で Visual C# SMO プロジェクトを作成する方法」を参照してください。

Visual Basic でのキャプチャ モードの有効化

このコードの例では、キャプチャ モードを有効化し、次に、キャプチャ バッファーに保持されている Transact-SQL コマンドを表示しています。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Set the execution mode to CaptureSql for the connection.
srv.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql
'Make a modification to the server that is to be captured.
srv.UserOptions.AnsiNulls = True
srv.Alter()
'Iterate through the strings in the capture buffer and display the captured statements.
Dim s As String
For Each s In srv.ConnectionContext.CapturedSql.Text
    Console.WriteLine(s)
Next
'Execute the captured statements.
srv.ConnectionContext.ExecuteNonQuery(srv.ConnectionContext.CapturedSql.Text)
'Revert to immediate execution mode. 
srv.ConnectionContext.SqlExecutionModes = SqlExecutionModes.ExecuteSql

Visual C# でのキャプチャ モードの有効化

このコードの例では、キャプチャ モードを有効化し、次に、キャプチャ バッファーに保持されている Transact-SQL コマンドを表示しています。

{ 
// Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
// Set the execution mode to CaptureSql for the connection. 
srv.ConnectionContext.SqlExecutionModes = SqlExecutionModes.CaptureSql; 
// Make a modification to the server that is to be captured. 
srv.UserOptions.AnsiNulls = true; 
srv.Alter(); 
// Iterate through the strings in the capture buffer and display the captured statements. 
string s; 
foreach ( String p_s in srv.ConnectionContext.CapturedSql.Text ) { 
   Console.WriteLine(p_s); 
} 
// Execute the captured statements. 
srv.ConnectionContext.ExecuteNonQuery(srv.ConnectionContext.CapturedSql.Text); 
// Revert to immediate execution mode. 
srv.ConnectionContext.SqlExecutionModes = SqlExecutionModes.ExecuteSql; 
}