I am looking to run this code here:
Write-Host "Running script"
$SQLServer4 = "ServerA"
$Database4 = 'master'
Invoke-Sqlcmd -ServerInstance $SQLServer4 -Database $Database4 -InputFile "C:\Users\Documents\Scripts\SaveSite.txt"
There is a commit statement in the script, it is commented out and you have to run it manually as long as the output looks good. This is fine and all when I do it in SSMS, but I am not sure how to run the commit statement from PowerShell.
I tried running the following:
Invoke-Sqlcmd -Query "commit" -ServerInstance "ServerA"
and I am getting this error:
Invoke-Sqlcmd : The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
Msg 3902, Level 16, State 1, Procedure , Line 1.
How would I go about this?
3条答案
按热度按时间iugsix8n1#
You can just concat
COMMIT
to the scriptvh0rcniy2#
Since you're using sqlcmd, you can use sqlcmd variables in your file. Here's a quick test I wired up:
Then, when you go to call it, you can optionally pass in a value for the commit variable
I would view it as a feature and not a bug that the case in which you're not passing in a variable warns you about the COMMIT variable not being defined. This is a signal to you that if you want to commit the results you've got to do something.
ovfsdjhp3#
The transaction is committed implicitly when the session ends.
If you need to hold a transaction open, you will not be able to use
Invoke-SqlCommand
Instead, you'll probably need to manually create and use ADO.Net objects likeSqlConnection
,SqlCommand
, andSqlTransaction
.This is a bad idea, btw. SQL Server will hold resources like locks until a transaction completes, making this a good way to create deadlocks on your server. Transactions are not intended for confirming long-running operations. Instead, they are intended for safe-guarding against errors/incompletions in complex operations that should still finish within a reasonable time. If you have complex operations with lower up-front confidence needing review, they should be pushed to a staging area in one (brief) transaction, then on confirmation pushed live in another (brief) transaction.