使用捕获模式

SMO 程序可以捕获和记录该程序发出的等效 Transact-SQL 语句,代替(或外加)该程序执行的语句。通过使用 ServerConnection 对象,或者通过使用 Server 对象的 ConnectionContext 属性,启用捕获模式。

示例

若要使用所提供的任何代码示例,您必须选择创建应用程序所需的编程环境、编程模板和编程语言。 有关详细信息,请参阅 SQL Server 联机丛书中的“How to: Create a Visual Basic SMO Project in Visual Studio .NET”或“How to: Create a Visual C# SMO Project in Visual Studio .NET”。

在 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 ( s in srv.ConnectionContext.CapturedSql.Text) { 
   Console.WriteLine(s); 
} 
//Execute the captured statements. 
srv.ConnectionContext.ExecuteNonQuery(srv.ConnectionContext.CapturedSql.Text); 
//Revert to immediate execution mode. 
srv.ConnectionContext.SqlExecutionModes = SqlExecutionModes.ExecuteSql; 
}