多个 Invoke-SqlCmd 和 Sql Server 事务 [英] Multiple Invoke-SqlCmd and Sql Server transaction
问题描述
如何确保以下语句在一个事务中运行?
How to make sure the following statements running in one transcation?
try
{
Invoke-SqlCmd -Query 'begin tran; ...sql script...'
# Other Powershell script
Invoke-SqlCmd -Query '...sql script...; if @@transcation > 0 commit tran'
}
catch
{
Invoke-SqlCmd -Query 'if @@transaction > 0 rollback tran;'
}
在事务中运行 Powershell 脚本的最佳方法是什么?
What's the best approach to run Powershell script in a transaction?
推荐答案
Invoke-sqlcmd 不支持 ADO.NET 事务.您有两种解决方法,或者将等效的 Powershell 代码写入此 MSDN 文档中显示的 C# 代码,用于 ADO.NET 事务:http://msdn.microsoft.com/en-us/library/2k2hy99x(v=vs.110).aspx
Invoke-sqlcmd doesn't support ADO.NET transcations. You have two workarounds, either write the equivalent Powershell code to the C# code shown in this MSDN documentation for ADO.NET transactions: http://msdn.microsoft.com/en-us/library/2k2hy99x(v=vs.110).aspx
或者使用 T-SQL 事务.在不向每个脚本添加 T-SQL Try/Catch 的情况下执行此操作的快速方法是将 XACAT_ABORT 设置为 ON;然后在开始和提交事务中包装脚本.请记住,这可能无法捕获终止错误:
Or use T-SQL transactions. A quick way of doing this without adding T-SQL Try/Catch to each script is to set XACAT_ABORT ON; then wrap script in begin and commit transaction. Keep in mind this may not catch terminating errors:
http://msdn.microsoft.com/en-us/library/ms188792.aspx
这篇关于多个 Invoke-SqlCmd 和 Sql Server 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!