Exception Handling in SQL Server by TRY CATCH Method


Exception Handling in SQL Server – Table of Content

Introduction to Exception handling in SQL server:

An Exception is nothing but an error mechanism that occurs in any program during the time of program execution.The methods used to resolve these errors are called Exception handling. Now Exception handling methods are widely used in the SQL Server because it’s easy to use methodology.There are several Exception handling available in SQL servers such as TRY and CATCH methods.We will be going to explain these sections later. SQL server 2005 has introduced the new Exception handling methods to help programs to run effortlessly and error-free. Sometimes it difficult to capture the errors which occurred during the time of end programming execution. Even user needs to know these kinds of mistakes happened in the end-users with programming codes.

To gain in-depth knowledge with practical experience in SQL server, then explore  SQL server Training!

TRY and CATCH methods:

SQL server 2005 has introduced these two methods to handle exceptions, such as TRY and CATCH. Both these TRY and CATCH statements work similarly to any other programming language. First, this statement is executed in the SQL server statement, which the user has written in the TRY block. If the Error occurred again, then TRY will automatically get executed the CATCH block.

EXAMPLE:

BEGIN TRY # executing first the TRY statement
// now insert the SQL statements
END TRY # ending of TRY statement
Now it’s time to execute the CATCH statement
BEGIN CATCH # executing the CATCH statement
// now this statement handle the exception details
END CATCH # ending of CATCH statement
The following are the numbers of Error handling property statements in the TRY…CATCH statements;
ERROR_NUMBER () # handling the Error in NUMBER property
ERROR_STATE () # handling the Error in STATE property
ERROR_SEVERITY () # handling the SEVERITY errors
ERROR_LINE () # handling the errors in LINE property
ERROR_PROCEDURE () # handling the PROCEDURAL errors
ERROR_MESSAGE () # handling the Message errors

NOTE: Normally, SQL Server stores the Error as a message; this Error has occurred in the execution of the following statement table;
Select * from sys.messages

HANDLING EXCEPTION using TRY AND CATCH statements:

In this section, I am going to explain the steps involved in handling the Exception using TRY and CATCH statements,

Steps:

Step1: user need to create the Custom error table with the name “Error Tracer,”

Step2: user needs to write the common stored procedure for handling the current Exception in the table name Proc_InsertErrorDetails, which helps the user insert the error details into the given step1 created table already.

Step3: Now, need to write a simple procedure and execute the exception handling statement using TRY……CATCH. When you get the errors, it will automatically call the Procs_InsertErrorDeatils and inserts the Error details.

Step4: Now, it’s time to check the ErrorTracer table that will list out all the occurred error details.

Programming example:

USE [Northwind] #create the NorthWind table 
GO
IF OBJECT_ID (‘databaseobject.ErrorTarcer’) IS NOT NULL value
BEGIN
DROP TABLE database object.ErrorTracer
PRINT ‘Table database object.ErrorTarcer Dropped’
END
GO

CREATE TABLE ErrorTracer
(
…………………
…………………# inserting table values
…………………..
)

IF OBJECT_ID (‘Proc_InsertErrorDetails’) IS NOT NULL

BEGIN
DROP PROCEDURE [databaseobject]. [Proc_InsertErrorDetails]
PRINT ‘procedure Proc_InsertErrorDetails Dropped’
END
GO

Syntax of Exception Handling:

TRY BLOCK
SET of SQL Statement
Throws error
> CATCH BLOCKS
Handling Exception
(Error log, Rollback)
The code is as follows;
/* SQL statements*/
END TRY #end of the try statement
BEGIN CATCH # start of the BEGIN statement
Print ERROR OR
ROLLBACK Transaction
END CATCH

In this Exception handling, SQL statements were inserted into try Blocks. If all the inserted statements were executed without any error, then the try statement ‘OK’ will go to the CATCH Block.

Types of SQL server Exceptions:

There are two types of SQL server Exceptions available; such as

  • System defined Exception handling
  • User-defined Exception handling

 Let us discuss them one by one,

System defined Exception handling:

The system defined Exception handling is the system generates nothing but Exceptions.

Example:

Declare @Valu1 int;
Declare @Valu2 int;
BEGIN TRY
Set @Valu1 = 9;
Set @Valu2 = @Valu1/0; /*Error has occurred */
END TRY
BEGIN CATCH
Print ‘An error occurred:’
Print Error_Message () /* property of exception handling
END CATCH

OUTPUT:
An Error Occurred
Divided by Zero error encountered

User-Defined Exception handling:

This type of Exception is generated by the users, not by any system.

SQL Server Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Programming example:

Declare @valu1 int;
Declare @valu2 int;
BEGIN TRY
Set @valu1 = 9;
Set @Valu2 = @Valu1 % 2;
If @Valu1 = 1
Print ‘Error Not occurred’
Else
BEGIN
Print ‘Error Occurs’;
Throw 80000, ‘Number is even’, 5
End

END TRY
BEGIN CATCH
Print ‘Error occurs that is: ‘
Print Error_Message ()
END CATCH

Output:

Error occurs
The Error occurs that is:
Number is even

Here 80000 denote the error number, and 5 represents the state where the error message has occurred.

System functions and keywords used within the CATCH block:

Now we are going to explain the few programming examples to define these functions and system keyword;
First, we need to create a table and enter some value into the table as follow;

CREATE TABLE emp
(
Emp_ID int Identify (1,1),
First_name Nvarchar (MAX) not Nullval,
Last_name Nvarchar (MAX) not Nullval,
Salary Int Not Null check (Salary > 20,000),
City Nvarchar (max) Not Nullval
)
Insert data into the table values;
Select ‘Kavya,’ ‘Gowda,’ 50000, ‘Alwar’ Union ALL
Select ‘Rahul,’ ‘chowdary,’ 25000, ‘Alwar’ Union ALL
Select ‘Sandeep,’ ‘Prajapati,’ 23000, ‘Alwar’ Union ALL
Select ‘Sanjeev,’ ‘Jangid,’ 27000, ‘Alwar’ Union ALL
Select ‘Neeraj,’ ‘Baldia,’ 24000, ‘Alwar’ Union ALL
Select ‘Narendra,’ ‘Saini,’ 22000, ‘Alwar’ Union ALL
è Now it’s time to execute the ‘SELECT’ statements by using the command,
Select * from Employee
Serl.no
Emp_id
First_name
Last_name
Salary
City

1
1
Kavya
Gowda
50000
Alwar

2
2
Rahul
Chowdary
25000
Alwar

3
3
Sandeep
Prajapat
23000
Alwar

4
4
Sanjeev
Jangid
27000
Alwar

5
5
Neeraj
Baldia
24000
Alwar

6
6
Narendra
Saini
22000
Alwar

Exception handling properties:

Example1: @ERROR;

This statement returns the error number for the last executed SQL statements. It returns zero if the previous transaction SQL statements were encountered, and it will not return an error number.

UPDATE Employee SET Salary = 20000 WHERE Emp_ID = 5
IF @ERROR = 547
PRINT ‘A check constraints violation error occurred. ‘;

Output:
Msg 557, level 14, State 0, Line 1

The UPDATE statement conflicted with the method CHECK constraint ‘CK_Employee_salary_68487DD7’.

Example 2: ERROR_NUMBER

This Exception handling property returns the number values which causes the errors. It would replace the ZERO if we called outside the CATCH block statement.

BEGIN TRY
UPDATE Employee SET salary_val = 20000 WHERE Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER () AS errorNumber;
END CATCH;

OUTPUT:
ERRORNUMBER = 557

Example 3:

ERROR_MESSAGE returns the errors which are caused by the messages. This returns the type of ERROR_MESSAGE is the type of nvarchar (5000).

BEGIN TRY
UPDATE Employee SET Salary =20000 WHERE EMP_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE () AS ERRORMSG;

END CATCH;

OUTPUT:
The UPDATE statement conflict the CHECK Constraint ‘CK_EMPLOYEE_SALARY_68487DD7’. This conflict method will be stored in HOME_MANAGMENT.

EXAMPLE 4: ERROR_STATE

ERROR_STATE returns the number of state errors. The data type of ERROR_STATE is Integer.

BEGIN TRY
SELECT SALARY+ FIRST _NAME from EMPLOYEE WHERE Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_STATE () AS ERRORState, ERROR_MESSAGE () ErrorMSG;
END CATCH;

OUTPUT:

ErrorState = 1
ErrorMsg = Conversion failed error message where it returns the value in Nvarchar.

Example 5: ERROR_LINE

ERROR_LINE exception handling returns the line number where the Error has occurred. The return type of ERROR_LINE is Integer.

BEGIN TRY
SELECT SALARY + First_name from Employee WHERE EMP_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_STATE () As ErrorLine;
END CATCH;

OUTPUT:
ErrorLine = 1

Example 6: ERROR_PROCEDURE

ERROR_PROCEDURE returned the name of the stored triggers and procedure when an error occurred. The return type is ERROR_PROCEDURE is nvarchar (128).

Join our BMC Marimba training today and enhance your skills to new heights!

HKR Trainings Logo

Subscribe to our YouTube channel to get new updates..!

RETURN VALUE:

Return Value Returns the stored procedure Name if any Error has occurred in the stored procedure or trigger once the CATCH statement is blocked.

It returns the NULL value if the Error does not occur within a stored procedure or any type of trigger that is called outside the CATCH block.

The code is as follows;

CREATE procedure My_prnc
AS
BEGIN TRY
SELECT SALARY + First_Name FROM Employee Where Emp_ID = 6
END TRY
BEGIN CATCH
SELECT ERROR_PROCEDURE () As Prnc;
END CATCH;
END

OUTPUT:
01. Exec My_Prnc,

Prnc:
My_Prnc

Example 7: ERROR_SEVERITY

ERROR_SEVERITY returns the severity of the Error. The data type of ERROR_SEVERITY is Int.

The code is as follows;

BEGIN TRY

SELECT SALARY + First_Name from Employee WHERE EMP_ID = 6

END TRY

BEGIN CATCH

SELECT ERROR_SEVERITY () AS ErrorSeverity;

END CATCH;

OUTPUT:

ErrorSeverity

16

The severity level of the error message provides an indication of error type that occurred in Microsoft SQL Server. In the below example the Severity level is 15 so the system will give you a message like Permission denied.

Some Important Severity levels are;
Serial.no of severity
Description

13
Which indicates the transaction deadlock errors

14
Indicates the security-related error levels, by that time system will generate an error message like permission denied

15
This severity indicates the syntax error in the form of Transact-SQL command

16
This severity level indicates the general errors that will be corrected by the user

TRANSACTION management in Exception handling

This is a very important type of exception handling; let’s get into the full details

BEGIN TRANSACTION Trans
BEGIN TRY
DELETE From Employee Where Employee. Emp_ID <4
UPDATE EMPLOYEE SET Employee. First_Name = ‘Kavya’ where Employee. EMP_ID = ‘5
IF @@TRANSCount > 0
BEGIN COMMIT Transaction Transt
END
END TRY
BEGIN CATCH
If @@TransCount > 0
Print ‘ERROR is occurred in Transaction’
BEGIN Rollback Transaction Transt
END
END CATCH
SELECT *FROM Employee

OUTPUT:
Serial number
Emp_id
First_name
Last_name
Salary
City

1
1
Kavya
Gowda
50000
Alwar

2
2
Rahul
Chowdary
25000
Alwar

3
3
Sandeep
Prajapat
23000
Alwar

4
4
Sanjeev
Jangid
27000
Alwar

5
5
Neeraj
Baldia
24000
Alwar

6
6
Narendra
Saini
22000
Alwar

Top 30 frequently asked Maximo Interview Questions!

SQL Server Certification Training

Weekday / Weekend Batches

INSIGHT:

In this article, I have explained the important concepts about Exception handling in SQL server. The Exception is nothing but Errors that occur during the time of programming execution.The mechanism which is used to handle the Errors is called Handling. And also I have explained the properties and types of the Exception handling mechanism in the SQL server.I hope this article may help a few of you to learn the important concepts of Error handling and also enables you to communicate with experts across the world via social forums.

Related Articles:

1. Isolation Levels in SQL Server

2. SQL Server Joins

3. SQL Server Data Tools



Source link

Leave a Reply

Subscribe to Our Newsletter

Get our latest articles delivered straight to your inbox. No spam, we promise.

Recent Reviews


ServiceNow Visual Task Board – Table of Content

Visual Task Boards

Visual Task Boards (VTB) change the route of lists and structures into an intuitive graphical experience. Using the Visual Task Boards, you could view and refresh various task records that show up as cards which can be transferred between paths. An action stream on the board shows recent action so you can undoubtedly follow changes to assignments. You could add task cards from any table which stretches out Task to naturally and effectively track refreshes and alter records straightforwardly from the board. Any client can utilize task sheets, paying little heed to the role, however access control rules (ACLs) may restrict which cards every client can see. The Visual Task Board interface gives a realistic rich climate appropriate for overseeing and working together on records. For instance, a supervisor may make a load up for the group to follow their appointed incidents by state continuously.

ServiceNow provides an incredible apparatus for keeping steady over your everyday obligations. Visual Task Boards change the drilling plan for the day into an intuitive and outwardly satisfying experience. They fill in as an incredible instrument for extensive undertakings with different colleagues where association is critical. Tasks are shown as cards which can be shifted across various paths to address the situation with that task. All progressions are followed continuously, so your group is consistently up to date on where assignments stand.

 Become a Servicenow Certified professional by learning this HKR Servicenow Training !

Types of Visual Task Boards

Visual Task Boards can be made in three unique designs: Freeform, Flexible and Guided. Every format has remarkable settings that oblige explicit necessities. For instance, Guided sheets are best for Project Managers who need to allot singular tasks to explicit individuals from the venture team. Users can likewise arrange their Visual Task Boards with swimlanes, an element that basically permits you to have the choice between a horizontal view or a vertical view, whichever you prefer. Three kinds of Visual Task Boards

  1. Freedom: Personal organizer
  2. Guided boards: Utilises incident states
  3. Flexible: From the list but lane alters to not update given task data

To begin with vtb, you can navigate to self-service > visual task boards and follow the instructions for creating a board

Acquire Tasktop certification by enrolling in the HKR Tasktop Training program in Hyderabad!

ServiceNow Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Create a data driven board

  • Go to Self-Service, then Visual Task Boards Next to My Task Boards, choose New, or if you have never created a task board before select Create New Visual TaskBoard .
  • In the Create New Board window, click Data DrivenBoard .
  • In the Task Table list, choose a base table of tasks where you can base your board, for example, an incident table.
  • (Optional)From the Lane Field list, choose the field you need to utilise for the lane headers. Make a Flexible board using editable headers by choosing None. The sort of board which is made and the lanes that show up on the board rely upon the kind of segment you choose. In the event that you choose a reference or decision section, the board is a guided board . Every path in a guided board addresses one potential value for that segment and the cards show up in the fitting lane. For instance, in the event that you make a guided task board for occurrences utilizing the State section, the board displays one lane for every episode state, like New or Closed . On the off chance that you choose a section that isn’t a reference or decision, the board is a flexible board and the board displays the default paths, To Do , Doing , and Done , with all cards in the To Do path.
  • (Optional)Make a filter to display the records you need to operate with. For instance, you may sift through occurrences that are not doled out to you. Any card which no longer suits the boundaries of the filter is automatically eliminated from the task board. 
  • (Optional)Select the board name and enter another name. Note: For guided sheets made from decision fields, like State, the framework makes a lane for every possible decision value. For guided sheets made from reference fields, the system makes a path just for each value being used by a task card. The lanes are included on a case by case basis if the reference field esteems change.

 Top 30 frequently asked Servicenow Interview Questions !

, others, servicenow-visual-task-board-description-0, , others, servicenow-visual-task-board-description-1

Subscribe to our YouTube channel to get new updates..!

Domain separation and Visual Task Boards

Support level: Basic

Visual task boards have domain division at the information level only. Domain separation is upheld in the Visual Task Boards application. Domain separation empowers you to isolate information, measures, and system assignments into intelligent groupings called domains. You can handle a few parts of this separation, including which clients can see and access information. 

Business rationale: This ensures that information goes into the legitimate domain for the application’s service organization use cases. The application upholds domain separation at run time. The domain separation incorporates partition from the UI,reporting, cache keys, rollups, and collections. The proprietor of the case should set up the application to work across numerous tenants. 

Use case: When a service provider (SP) utilizes chat to react to an tenant client’s message, the customer should have the option to view the SP’s reaction. 

How does domain separation operates in Visual Task Boards

Visual Task Boards which are “information driven” displays the information from tables that resemble Task tables. The information that is domain isolated is additionally supported. Condition-based models are utilized to channel that information. Freestyle VTBs utilize Private Tasks (vtb_task), that upholds domain separation as an expansion of Task and acquires domain separation rationale accordingly.

Want to know more about Servicenow,visit here Servicenow Tutorial !

Benefits of Visual Task Boards (VTB)

  • Picturize your methods through an intuitive drag and drop interface to distinguish measure bottlenecks initially, and in real time. 
  • Change the manner in which you see your work by survey records or inquiries as a task board as simple as right-tapping on a list. Immediately make freestyle task boards to handle ad hoc methods whenever you require them. 
  • Stay up to date with an embedded action stream to guarantee that you could see all updates in a single spot, regardless of whether you join the discussion late.

ServiceNow Training

Weekday / Weekend Batches

Conclusion

You can change your lists and structures into an intuitive graphical experience utilizing Visual Task Boards (VTB) It also allow you to deal with your taks through a visual, intuitive interface and recognize process bottlenecks at a glance, in real-time along with tracking embedded activity monitors to see updates all in one place.Utilize visual  task boards to make your own daily agenda, team up continuously with group individuals on tasks, and more. Shown graphically as lanes and cards, vtb gives a page to see and arrange all your work in servicenow.

Related Article:



Source link