2013-06-19 185 views
0

我有一个从数据库(MS SQL 2008)读取计算机信息行并将其存储到读取器中的PowerShell。如何处理交易异常

# Open the database connection 
$conn.Open() 

# Create and execute the SQL Query 

$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) 

$rdr = $cmd.ExecuteReader() 

# Read Computer Information into multidimensional array 
$count=0 
while ($rdr.read()){ 
    $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), 
    $rdr.GetValue(3)) 
    $count=$count + 1 
} 


# Close the database connection 
$conn.Close()  

Write-host Finished reading $count IP addresses from database 

约50%的时间,我得到一个异常

异常调用 “读” 和 “0” 的参数(一个或多个):“事务(进程 ID 107)中的上锁定僵持资源与另一个进程,并已被选为死锁受害者,重新运行交易。“在 C:\ script.ps1:83字符:17 +而($ rdr.read < < < <()){ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException

我在数据库中有大约18,000台计算机。当抛出这个异常时,它只能读取10,000个,它随时间变化。

如何处理异常,以便它读取所有18,000台计算机?

回答

1

尝试包裹在try..catch块的执行和循环是这样的:

$conn.Open() 
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) 

do { try { 
    $rdr = $cmd.ExecuteReader() 

    $count=0 
    while ($rdr.read()) { 
     $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), 
         $rdr.GetValue(3)) 
     $count=$count + 1 
    } 

    $transactionComplete = $true } catch { $transactionComplete = $false } } until ($transactionComplete) 

$conn.Close()

然而,更好的方法是识别和避免死锁状态(如果可能)。

+0

会试试这个 - 谢谢 – Rhonda

+0

不客气。如果您发现它能解决您的问题,请考虑[接受答案](http://meta.stackexchange.com/a/5235)。 –