SQL Server Committng SQL transactions from PowerShell

cedebl8k  于 2023-04-04  发布在  Shell
关注(0)|答案(3)|浏览(196)

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?

iugsix8n

iugsix8n1#

You can just concat COMMIT to the script

Write-Host "Running script"

$SQLServer4 = "ServerA" 
$Database4 = 'master'

$script = Get-Content -Path "C:\Users\Documents\Scripts\SaveSite.txt" -Raw;

$script += "
IF @@TRANCOUNT > 0
    COMMIT;
";

Invoke-Sqlcmd -ServerInstance $SQLServer4 -Database $Database4 -Query $script;
vh0rcniy

vh0rcniy2#

Since you're using sqlcmd, you can use sqlcmd variables in your file. Here's a quick test I wired up:

if ('$(COMMIT)' = '1')
   print 'committing';
else
   print 'not committing';

Then, when you go to call it, you can optionally pass in a value for the commit variable

C:\temp
> sqlcmd -S . -E -i .\sqlcmd-test.sql -v COMMIT=1
committing
C:\temp
> sqlcmd -S . -E -i .\sqlcmd-test.sql
'COMMIT' scripting variable not defined.
not committing
C:\temp
>

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.

ovfsdjhp

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 like SqlConnection , SqlCommand , and SqlTransaction .

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.

相关问题