我最近发布了一个新模块,用于与支持事务的数据库进行交互:
Install-Module -Name InvokeQuery
如果发生错误,您不需要显式回滚。创建的环境事务Start-Transaction
将为您处理。
try {
$db = "test"
Start-Transaction
$sql = "insert into table1 values (NEWID(), 8765, 'transactions!', GETDATE())"
$rowcount = $sql | Invoke-SqlServerQuery -Database $db -UseTransaction -CUD -Verbose
Write-Host "Inserted $rowcount rows!"
$sql = "insert into table1 values (NEWID(), 5555, 'transaction too!', GETDATE())"
$rowcount = $sql | Invoke-SqlServerQuery -Database $db -UseTransaction -CUD -Verbose
Write-Host "Inserted $rowcount rows!"
Complete-Transaction
}
catch {
##Transaction will automatically be rolled back....
Write-Error $_
}
如果要在事务中显式回滚,则抛出错误:
throw 'rollback because of reason X!'
更多示例:
https ://github.com/ctigeek/InvokeQueryPowershellModule/blob/master/README.md#transactions