从 .Net 4.5 开始,SqlCommand
类有ExecuteReaderAsync()
方法,SqlDataReader
类有ReadAsync()
方法。一旦 SQL Server 开始使用这些新方法将数据发送到客户端,就可以开始处理数据。
不幸的是,PowerShell 中没有 await 运算符,因此代码看起来不如 C# 中的漂亮。
$sqlInstance = 'SqlServerName';
$con = New-Object System.Data.SqlClient.SQLConnection;
$con.ConnectionString = "Data Source=$($sqlInstance);Integrated Security=SSPI;Asynchronous Processing=true;";
$con.Open();
$cmd = New-Object System.Data.SqlClient.SQLCommand;
$cmd.Connection = $con;
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
$cmd.CommandText = 'xp_readerrorlog';
# add parameters
$cmd.Parameters.Add('p1', [System.Data.SqlDbType]::Int, 1) | out-null;
$cmd.Parameters['p1'].Value = 1;
$cmd.Parameters.Add('p2', [System.Data.SqlDbType]::Int, 1) | out-null;
$cmd.Parameters['p2'].Value = 1;
$cmd.Prepare();
$task = $cmd.ExecuteReaderAsync();
# wait for first rows
While ( $task.IsCompleted -ne $true ) {
Start-Sleep -m 10;
}
# PowerShell does not have await operator so a SqlDataReader object can be retrieved this way
$reader = $task.GetAwaiter().GetResult();
# read first row
$reader.ReadAsync().GetAwaiter().GetResult() | out-null;
$reader['LogDate'];
$cmd.Cancel(); # cancel execution, there is no need to wait for the whole recordset to be transfered to the client
$con.Close();