Created
August 18, 2022 16:27
-
-
Save Warrenn/10c779deaa386a999c29a6809b6c2569 to your computer and use it in GitHub Desktop.
execute database update insert or delete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Execute-NonQuery([psobject[]]$sqlCommands, $connectionString) { | |
$connection = new-object system.data.SqlClient.SQLConnection($connectionString) | |
$connection.Open() | |
$command = $connection.CreateCommand() | |
$transaction = $connection.BeginTransaction() | |
$command.Connection = $connection | |
$command.Transaction = $transaction | |
try { | |
for($i=0;$i -lt $sqlCommands.Length;$i++){ | |
$command.CommandText = $sqlCommands[$i].commandText | |
$parameters = $sqlCommands[$i].parameters | |
$command.Parameters.Clear() | |
$parameters | Select-Object -ExpandProperty Keys | %{ | |
$command.Parameters.Add($_, $parameters[$_]) | |
} | |
$command.ExecuteNonQuery() | |
} | |
$transaction.Commit() | |
} | |
catch { | |
$transaction.Rollback() | |
} | |
finally { | |
$connection.Close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment