SQL Transaction query with Try Catch Block
Quando si effettua una transazione è bene associarla ad un blocco TRY .. CATCH.. ed ottenere l’eventuale errore che scatena il ROLLBACK della transazione.
Ecco lo snippet di esempio:
USE [Northwind] GO /* Specifica se in SQL Server viene eseguito automaticamente il rollback della transazione corrente quando un'istruzione Transact-SQL genera un errore di run-time. */ SET XACT_ABORT ON; GO /* Inizio blocco TRY */ BEGIN TRY /* Inizio blocco TRANSAZIONE */ BEGIN TRAN -- ELENCO STATEMENT --OK INSERT INTO Categories([CategoryName], [Description], [Picture]) VALUES ('Cat1', 'Description Cat 1', NULL) -- KO -> FALLISCE LA TRANSAZIONE INSERT INTO Categories([CategoryName], [Description], [Picture]) VALUES (NULL, NULL, NULL) -- OK INSERT INTO Categories([CategoryName], [Description], [Picture]) VALUES ('Cat2', 'Description Cat 2', NULL) /* Fine blocco TRY */ END TRY /* Inizio blocco CATCH */ BEGIN CATCH IF (XACT_STATE()) = -1 BEGIN --Annullamento della transazione ROLLBACK TRAN --Mi faccio restituire l'errore SELECT ERROR_LINE() as ErrorLine, ERROR_MESSAGE() as ErrorMessage; END /* Fine blocco CATCH */ END CATCH IF (XACT_STATE()) = 1 BEGIN --Commit della Transazione COMMIT TRAN END
Nell’esempio precedente l’errore restituito sarà Cannot insert the value NULL into column ‘CategoryName’, table ‘Northwind.dbo.Categories’; column does not allow nulls. INSERT fails.
Viene effettuato dunque il rollback della transazione.
Downloas source: SQL_Transaction_query_with_Try_Catch_Block.zip (711,00 bytes)
1 commento