Vérifier @@TRANCOUNT dans une construction TRY...CATCH
Le ou la titulaire du compte 10 a gagné un tirage et recevra 200 \(. Vous préparez un petit script pour ajouter ces 200 \) au current_balance du compte 10. Vous pensez avoir tout bien écrit, mais vous préférez valider votre code.
En fait, vous avez fait une petite erreur en ajoutant l'argent : SET current_balance = 'current_balance' + 200. Vous avez écrit 'current_balance' comme une chaîne de caractères, ce qui génère une erreur.
Le script que vous créez doit faire un rollback de tous les changements en cas d'erreur, après avoir vérifié s'il y a une transaction ouverte. Si tout se passe bien, la transaction doit être validée (commit), là aussi après avoir vérifié s'il y a une transaction ouverte.
Cette activité fait partie du cours
Transactions et gestion des erreurs dans SQL Server
Instructions de l’exercice
- Démarrez la transaction.
- Corrigez l'erreur dans l'opération.
- Dans le bloc
TRY, vérifiez s'il y a une transaction et validez-la (commit). - Dans le bloc
CATCH, vérifiez s'il y a une transaction et annulez-la (rollback).
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
BEGIN TRY
-- Begin the transaction
___ ___;
-- Correct the mistake
UPDATE accounts SET current_balance = 'current_balance' + 200
WHERE account_id = 10;
-- Check if there is a transaction
IF ___ > 0
-- Commit the transaction
___ ___;
SELECT * FROM accounts
WHERE account_id = 10;
END TRY
BEGIN CATCH
SELECT 'Rolling back the transaction';
-- Check if there is a transaction
IF ___ > 0
-- Rollback the transaction
___ ___;
END CATCH