我正在寫一個PowerShell腳本,從數據庫中提取任意的SQL查詢。這些查詢可能會變得非常大,在嘗試sqlcmd後,我最終得到了StreamWriter/SqlCommand組合。我遇到的問題是執行速度有點慢。像10倍一樣慢。我被告知它應該更快,因此問題。 要代碼!Powershell SqlCommand和StreamWriter慢寫
$conn.ChangeDatabase("MyDB")
$mycmd = new-object System.Data.SqlClient.SqlCommand($Myquery, $conn)
$mycmd.CommandType = [System.Data.CommandType]::Text
$mycmd.CommandTimeout = 300
echo "Executing Reader."
$Results = $mycmd.ExecuteReader()
echo "Opening file for writing."
$sw2 = new-object system.IO.StreamWriter($sqlOutput, 1)
echo "File Opened for Writing."
$delimiter = ","
echo "Starting Row Reading"
$Counter = $Results.FieldCount
echo $Counter
# Put in header row on first execution.
$currtext = ""
if ($Counter -gt 0)
{
echo "Writing Header Row as:"
for ($i = 0; $i -lt $Counter; $i++)
{
$currtext = $currtext + $Results.GetName($i)
if ($i -lt $Counter - 1)
{$currtext = $currtext + $delimiter}
}
echo $currtext
$sw2.writeline($currtext)
$firstexecution = 0
}
else
{
$sw2.writeline("No Data Found")
}
$rowcount = 0
while ($Results.Read())
{
$rowcount = $rowcount + 1
#echo "Reading Row"
$i = 0
$currtext = ""
for ($i = 0; $i -lt $Counter; $i++)
{
#echo "Processing Row"
$currtext = $currtext + """" + [string]$Results[$i] + """"
if ($i -lt $Counter - 1)
{ $currtext = $currtext + $delimiter }
}
#echo "Writing Line."
#echo $currtext
$sw2.writeline($currtext)
}
echo "Total Rowcount:" + $rowcount
$sw2.flush()
$sw2.close()
$sw2.dispose()
$Results.close()
任何人都知道我在做什麼錯誤/如何解決它?通過行
$DBComputers = Invoke-Sqlcmd -ServerInstance $SQLServer -Username $SQLUsername -Password $SQLPassword `
-Database $SQLDatabase -Query "SELECT * FROM Physical WHERE Retired=0 AND OS LIKE '%Windows%' ORDER BY Name"
Iteriate:
如果你真的說它變慢時,它會有很多幫助。在劇本中你有很多回應,那麼在它真的很慢之前最後一條消息是什麼?此外,sqlcmd可能會更快(我還沒有測試過),因爲使用powershell時需要生成對象等,而sqlcmd只需寫下未分析的行。 – 2013-03-19 17:07:33
從性能的角度來看,重要的塊是逐行讀取,即while循環的部分。 while循環可以每分鐘讀取/寫入大約五兆字節的數據,這看起來很慢。 – 2013-03-19 17:23:45