Advertisement
Guest User

StoredProcedureWithError

a guest
Feb 6th, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 2.02 KB | None | 0 0
  1. USE [example_database]
  2. GO
  3. /****** Object:  StoredProcedure [dbo].[test_error_cannot_insert_null]    Script Date: 2/6/2019 1:59:21 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. -- =============================================
  9. -- Author:      Gary Reckard
  10. -- Create date: 2019-06-19
  11. -- Description: testing error reporting from calling procedures
  12. -- =============================================
  13. ALTER PROCEDURE [dbo].[test_error_cannot_insert_null]
  14. AS
  15. BEGIN
  16.  
  17.     DECLARE @TranCounter INT;  
  18.     SET @TranCounter = @@TRANCOUNT;  
  19.     IF @TranCounter > 0  
  20.         SAVE TRANSACTION ProcedureSave;  
  21.     ELSE  
  22.         BEGIN TRANSACTION;
  23.  
  24.     SET XACT_ABORT ON;
  25.  
  26.     BEGIN TRY
  27.    
  28.         --------------------------------------------------
  29.         -------------///// BEGIN SQL \\\\\----------------
  30.         --------------------------------------------------
  31.  
  32.             --this should fail!
  33.             INSERT INTO [roles]
  34.                 (
  35.                     name,
  36.                     description
  37.                 )
  38.             VALUES
  39.                 (
  40.                     null,
  41.                     null
  42.                 );
  43.  
  44.         --------------------------------------------------
  45.         --------------\\\\\ END SQL /////-----------------
  46.         --------------------------------------------------
  47.  
  48.  
  49.         IF @TranCounter = 0  
  50.             COMMIT TRANSACTION;
  51.  
  52.  
  53.     END TRY
  54.     BEGIN CATCH        
  55.         DECLARE @errorProcedure varchar(100) = ERROR_PROCEDURE(),
  56.                 @errorShort varchar(255)     = ERROR_MESSAGE(),
  57.                 @errorCode varchar(50)       = ERROR_NUMBER(),
  58.                 @errorLine int               = ERROR_LINE(),  
  59.                 @errorSeverity int           = ERROR_SEVERITY(),
  60.                 @errorState int              = ERROR_STATE(),  
  61.                 @xstate int                  = XACT_STATE();
  62.  
  63.         if @xstate = -1                      ROLLBACK TRANSACTION;  
  64.         if @xstate = 1 and @TranCounter = 0  ROLLBACK TRANSACTION;  
  65.         if @xstate = 1 and @TranCounter > 0  ROLLBACK TRANSACTION ProcedureSave;  
  66.        
  67.         -- Log errors
  68.         EXEC errors_add @errorCode, @errorProcedure,  @errorShort, NULL, @errorLine, @errorSeverity, @errorState, @xstate;
  69.  
  70.         THROW;
  71.         RETURN;
  72.     END CATCH          
  73.  
  74. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement