{"id":1899,"date":"2019-05-01T08:32:21","date_gmt":"2019-05-01T01:32:21","guid":{"rendered":"http:\/\/www.sqlservertutorial.net\/?page_id=1899"},"modified":"2020-04-11T20:12:14","modified_gmt":"2020-04-11T13:12:14","slug":"sql-server-try-catch","status":"publish","type":"page","link":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/","title":{"rendered":"SQL Server TRY CATCH"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the SQL Server <code>TRY CATCH<\/code> construct to handle exceptions in stored procedures.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='sql-server-try-catch-overview'>SQL Server TRY CATCH overview <a href=\"#sql-server-try-catch-overview\" class=\"anchor\" id=\"sql-server-try-catch-overview\" title=\"Anchor for SQL Server &lt;code&gt;TRY CATCH&lt;\/code&gt; overview\">#<\/a><\/h2>\n\n\n\n<p>The <code>TRY CATCH<\/code> construct allows you to gracefully handle exceptions in SQL Server. To use the <code>TRY CATCH<\/code> construct, you first place a group of Transact-SQL statements that could cause an exception in a <code>BEGIN TRY...END TRY<\/code> block as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">BEGIN<\/span> TRY  \n   <span class=\"hljs-comment\">-- statements that may cause exceptions<\/span>\n<span class=\"hljs-keyword\">END<\/span> TRY  \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Then you use a <code>BEGIN CATCH...END CATCH<\/code> block immediately after the <code>TRY<\/code> block:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">BEGIN<\/span> CATCH  \n   <span class=\"hljs-comment\">-- statements that handle exception<\/span>\n<span class=\"hljs-keyword\">END<\/span> CATCH  \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following illustrates a complete <code>TRY CATCH<\/code> construct:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">BEGIN<\/span> TRY  \n   <span class=\"hljs-comment\">-- statements that may cause exceptions<\/span>\n<span class=\"hljs-keyword\">END<\/span> TRY \n<span class=\"hljs-keyword\">BEGIN<\/span> CATCH  \n   <span class=\"hljs-comment\">-- statements that handle exception<\/span>\n<span class=\"hljs-keyword\">END<\/span> CATCH  \n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>If the statements between the <code>TRY<\/code> block complete without an error, the statements between the <code>CATCH<\/code> block will not execute. However, if any statement inside the <code>TRY<\/code> block causes an exception, the control transfers to the statements in the <code>CATCH<\/code> block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='the-catch-block-functions'>The CATCH block functions <a href=\"#the-catch-block-functions\" class=\"anchor\" id=\"the-catch-block-functions\" title=\"Anchor for The &lt;code&gt;CATCH&lt;\/code&gt; block functions\">#<\/a><\/h3>\n\n\n\n<p>Inside the <code>CATCH<\/code> block, you can use the following functions to get the detailed information on the error that occurred:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>ERROR_LINE()<\/code> returns the line number on which the exception occurred.<\/li><li><code>ERROR_MESSAGE()<\/code> returns the complete text of the generated error message.<\/li><li><code>ERROR_PROCEDURE()<\/code> returns the name of the stored procedure or trigger where the error occurred.<\/li><li><code>ERROR_NUMBER()<\/code> returns the number of the error that occurred.<\/li><li><code>ERROR_SEVERITY()<\/code> returns the severity level of the error that occurred.<\/li><li><code>ERROR_STATE()<\/code> returns the state number of the error that occurred.<\/li><\/ul>\n\n\n\n<p>Note that you only use these functions in the <code>CATCH<\/code> block. If you use them outside of the <code>CATCH<\/code> block, all of these functions will return <code><a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-basics\/sql-server-null\/\">NULL<\/a><\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='nested-try-catch-constructs'>Nested TRY CATCH constructs <a href=\"#nested-try-catch-constructs\" class=\"anchor\" id=\"nested-try-catch-constructs\" title=\"Anchor for Nested &lt;code&gt;TRY CATCH&lt;\/code&gt; constructs\">#<\/a><\/h3>\n\n\n\n<p>You can nest <code>TRY CATCH<\/code> construct inside another <code>TRY CATCH<\/code> construct. However, either a <code>TRY<\/code> block or a <code>CATCH<\/code> block can contain a nested <code>TRY CATCH<\/code>, for example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">BEGIN<\/span> TRY\n    <span class=\"hljs-comment\">--- statements that may cause exceptions<\/span>\n<span class=\"hljs-keyword\">END<\/span> TRY\n<span class=\"hljs-keyword\">BEGIN<\/span> CATCH\n    <span class=\"hljs-comment\">-- statements to handle exception<\/span>\n    <span class=\"hljs-keyword\">BEGIN<\/span> TRY\n        <span class=\"hljs-comment\">--- nested TRY block<\/span>\n    <span class=\"hljs-keyword\">END<\/span> TRY\n    <span class=\"hljs-keyword\">BEGIN<\/span> CATCH\n        <span class=\"hljs-comment\">--- nested CATCH block<\/span>\n    <span class=\"hljs-keyword\">END<\/span> CATCH\n<span class=\"hljs-keyword\">END<\/span> CATCH\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='sql-server-try-catch-examples'>SQL Server TRY CATCH examples <a href=\"#sql-server-try-catch-examples\" class=\"anchor\" id=\"sql-server-try-catch-examples\" title=\"Anchor for SQL Server &lt;code&gt;TRY CATCH&lt;\/code&gt; examples\">#<\/a><\/h2>\n\n\n\n<p>First, <a href=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/basic-sql-server-stored-procedures\/\">create a stored procedure<\/a> named <code>usp_divide<\/code> that divides two numbers:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> PROC usp_divide(\n    @a <span class=\"hljs-built_in\">decimal<\/span>,\n    @b <span class=\"hljs-built_in\">decimal<\/span>,\n    @c <span class=\"hljs-built_in\">decimal<\/span> <span class=\"hljs-keyword\">output<\/span>\n) <span class=\"hljs-keyword\">AS<\/span>\n<span class=\"hljs-keyword\">BEGIN<\/span>\n    <span class=\"hljs-keyword\">BEGIN<\/span> TRY\n        <span class=\"hljs-keyword\">SET<\/span> @c = @a \/ @b;\n    <span class=\"hljs-keyword\">END<\/span> TRY\n    <span class=\"hljs-keyword\">BEGIN<\/span> CATCH\n        <span class=\"hljs-keyword\">SELECT<\/span>  \n            ERROR_NUMBER() <span class=\"hljs-keyword\">AS<\/span> ErrorNumber  \n            ,ERROR_SEVERITY() <span class=\"hljs-keyword\">AS<\/span> ErrorSeverity  \n            ,ERROR_STATE() <span class=\"hljs-keyword\">AS<\/span> ErrorState  \n            ,ERROR_PROCEDURE() <span class=\"hljs-keyword\">AS<\/span> ErrorProcedure  \n            ,ERROR_LINE() <span class=\"hljs-keyword\">AS<\/span> ErrorLine  \n            ,ERROR_MESSAGE() <span class=\"hljs-keyword\">AS<\/span> ErrorMessage;  \n    <span class=\"hljs-keyword\">END<\/span> CATCH\n<span class=\"hljs-keyword\">END<\/span>;\nGO\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this stored procedure, we placed the formula inside the <code>TRY<\/code> block and called the <code>CATCH<\/code> block functions <code>ERROR_*<\/code> inside the <code>CATCH<\/code> block.<\/p>\n\n\n\n<p>Second, call the <code>usp_divide<\/code> stored procedure to divide 10 by 2:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">DECLARE<\/span> @r <span class=\"hljs-built_in\">decimal<\/span>;\nEXEC usp_divide 10, 2, @r output;\nPRINT @r;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here is the output<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">5\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Because no exception occurred in the <code>TRY<\/code> block, the stored procedure completed at the <code>TRY<\/code> block.<\/p>\n\n\n\n<p>Third, attempt to divide 20 by zero by calling the <code>usp_divide<\/code> stored procedure:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">DECLARE<\/span> @r2 <span class=\"hljs-built_in\">decimal<\/span>;\nEXEC usp_divide 10, 0, @r2 output;\nPRINT @r2;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following picture shows the output:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"538\" height=\"38\" src=\"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png\" alt=\"SQL Server TRY CATCH Example\" class=\"wp-image-1900\" srcset=\"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png 538w, https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example-300x21.png 300w\" sizes=\"auto, (max-width: 538px) 100vw, 538px\" \/><\/figure>\n\n\n\n<p>Because of division by zero error which was caused by the formula, the control was passed to the statement inside the <code>CATCH<\/code> block which returned the error&#8217;s detailed information.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='sql-serer-try-catch-with-transactions'>SQL Serer TRY CATCH with transactions <a href=\"#sql-serer-try-catch-with-transactions\" class=\"anchor\" id=\"sql-serer-try-catch-with-transactions\" title=\"Anchor for SQL Serer &lt;code&gt;TRY CATCH&lt;\/code&gt; with transactions\">#<\/a><\/h2>\n\n\n\n<p>Inside a <code>CATCH<\/code> block, you can test the state of transactions by using the <code>XACT_STATE()<\/code> function.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>If the <code>XACT_STATE()<\/code> function returns -1, it means that an uncommittable transaction is pending, you should issue a <code>ROLLBACK TRANSACTION<\/code> statement.<\/li><li>In case the <code>XACT_STATE()<\/code> function returns 1, it means that a committable transaction is pending. You can issue a <code>COMMIT TRANSACTION<\/code> statement in this case.<\/li><li>If the <code>XACT_STATE()<\/code> function return 0, it means no transaction is pending, therefore, you don&#8217;t need to take any action.<\/li><\/ul>\n\n\n\n<p>It is a good practice to test your transaction state before issuing a <code>COMMIT TRANSACTION<\/code> or <code>ROLLBACK TRANSACTION<\/code> statement in a <code>CATCH<\/code> block to ensure consistency.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id='using-try-catch-with-transactions-example'>Using TRY CATCH with transactions example <a href=\"#using-try-catch-with-transactions-example\" class=\"anchor\" id=\"using-try-catch-with-transactions-example\" title=\"Anchor for Using &lt;code&gt;TRY CATCH&lt;\/code&gt; with transactions example\">#<\/a><\/h3>\n\n\n\n<p>First, set up two new tables <code>sales.persons<\/code> and <code>sales.deals<\/code> for demonstration:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.persons\n(\n    person_id  <span class=\"hljs-built_in\">INT<\/span>\n    PRIMARY <span class=\"hljs-keyword\">KEY<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span>, \n    first_name <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">100<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>, \n    last_name  <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">100<\/span>) <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>\n);\n\n<span class=\"hljs-keyword\">CREATE<\/span> <span class=\"hljs-keyword\">TABLE<\/span> sales.deals\n(\n    deal_id   <span class=\"hljs-built_in\">INT<\/span>\n    PRIMARY <span class=\"hljs-keyword\">KEY<\/span> <span class=\"hljs-keyword\">IDENTITY<\/span>, \n    person_id <span class=\"hljs-built_in\">INT<\/span> <span class=\"hljs-keyword\">NOT<\/span> <span class=\"hljs-literal\">NULL<\/span>, \n    deal_note <span class=\"hljs-keyword\">NVARCHAR<\/span>(<span class=\"hljs-number\">100<\/span>), \n    <span class=\"hljs-keyword\">FOREIGN<\/span> <span class=\"hljs-keyword\">KEY<\/span>(person_id) <span class=\"hljs-keyword\">REFERENCES<\/span> sales.persons(\n    person_id)\n);\n\n<span class=\"hljs-keyword\">insert<\/span> <span class=\"hljs-keyword\">into<\/span> \n    sales.persons(first_name, last_name)\n<span class=\"hljs-keyword\">values<\/span>\n    (<span class=\"hljs-string\">'John'<\/span>,<span class=\"hljs-string\">'Doe'<\/span>),\n    (<span class=\"hljs-string\">'Jane'<\/span>,<span class=\"hljs-string\">'Doe'<\/span>);\n\n<span class=\"hljs-keyword\">insert<\/span> <span class=\"hljs-keyword\">into<\/span> \n    sales.deals(person_id, deal_note)\n<span class=\"hljs-keyword\">values<\/span>\n    (<span class=\"hljs-number\">1<\/span>,<span class=\"hljs-string\">'Deal for John Doe'<\/span>);\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Next, create a new stored procedure named <code>usp_report_error<\/code> that will be used in a <code>CATCH<\/code> block to report the detailed information of an error:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> PROC usp_report_error\n<span class=\"hljs-keyword\">AS<\/span>\n    <span class=\"hljs-keyword\">SELECT<\/span>   \n        ERROR_NUMBER() <span class=\"hljs-keyword\">AS<\/span> ErrorNumber  \n        ,ERROR_SEVERITY() <span class=\"hljs-keyword\">AS<\/span> ErrorSeverity  \n        ,ERROR_STATE() <span class=\"hljs-keyword\">AS<\/span> ErrorState  \n        ,ERROR_LINE () <span class=\"hljs-keyword\">AS<\/span> ErrorLine  \n        ,ERROR_PROCEDURE() <span class=\"hljs-keyword\">AS<\/span> ErrorProcedure  \n        ,ERROR_MESSAGE() <span class=\"hljs-keyword\">AS<\/span> ErrorMessage;  \nGO\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Then, develop a new stored procedure that deletes a row from the <code>sales.persons<\/code> table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">CREATE<\/span> PROC usp_delete_person(\n    @person_id <span class=\"hljs-built_in\">INT<\/span>\n) <span class=\"hljs-keyword\">AS<\/span>\n<span class=\"hljs-keyword\">BEGIN<\/span>\n    <span class=\"hljs-keyword\">BEGIN<\/span> TRY\n        <span class=\"hljs-keyword\">BEGIN<\/span> <span class=\"hljs-keyword\">TRANSACTION<\/span>;\n        <span class=\"hljs-comment\">-- delete the person<\/span>\n        <span class=\"hljs-keyword\">DELETE<\/span> <span class=\"hljs-keyword\">FROM<\/span> sales.persons \n        <span class=\"hljs-keyword\">WHERE<\/span> person_id = @person_id;\n        <span class=\"hljs-comment\">-- if DELETE succeeds, commit the transaction<\/span>\n        <span class=\"hljs-keyword\">COMMIT<\/span> <span class=\"hljs-keyword\">TRANSACTION<\/span>;  \n    <span class=\"hljs-keyword\">END<\/span> TRY\n    <span class=\"hljs-keyword\">BEGIN<\/span> CATCH\n        <span class=\"hljs-comment\">-- report exception<\/span>\n        EXEC usp_report_error;\n        \n        <span class=\"hljs-comment\">-- Test if the transaction is uncommittable.  <\/span>\n        IF (XACT_STATE()) = -1  \n        <span class=\"hljs-keyword\">BEGIN<\/span>  \n            PRINT  N<span class=\"hljs-string\">'The transaction is in an uncommittable state.'<\/span> +  \n                    <span class=\"hljs-string\">'Rolling back transaction.'<\/span>  \n            <span class=\"hljs-keyword\">ROLLBACK<\/span> <span class=\"hljs-keyword\">TRANSACTION<\/span>;  \n        <span class=\"hljs-keyword\">END<\/span>;  \n        \n        <span class=\"hljs-comment\">-- Test if the transaction is committable.  <\/span>\n        IF (XACT_STATE()) = 1  \n        <span class=\"hljs-keyword\">BEGIN<\/span>  \n            PRINT N<span class=\"hljs-string\">'The transaction is committable.'<\/span> +  \n                <span class=\"hljs-string\">'Committing transaction.'<\/span>  \n            <span class=\"hljs-keyword\">COMMIT<\/span> <span class=\"hljs-keyword\">TRANSACTION<\/span>;     \n        <span class=\"hljs-keyword\">END<\/span>;  \n    <span class=\"hljs-keyword\">END<\/span> CATCH\n<span class=\"hljs-keyword\">END<\/span>;\nGO\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this stored procedure, we used the <code>XACT_STATE()<\/code> function to check the state of the transaction before performing <code>COMMIT TRANSACTION<\/code> or <code>ROLLBACK TRANSACTION<\/code> inside the <code>CATCH<\/code> block.<\/p>\n\n\n\n<p>After that, call the <code>usp_delete_person<\/code> stored procedure to delete the person id 2:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_delete_person 2;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>There was no exception occurred.<\/p>\n\n\n\n<p>Finally, call the stored procedure <code>usp_delete_person<\/code> to delete person id 1:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\">EXEC usp_delete_person 1;\n<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The following error occurred:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"854\" height=\"42\" src=\"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Transaction-Example.png\" alt=\"SQL Server TRY CATCH Transaction Example\" class=\"wp-image-1901\" srcset=\"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Transaction-Example.png 854w, https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Transaction-Example-300x15.png 300w, https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Transaction-Example-768x38.png 768w\" sizes=\"auto, (max-width: 854px) 100vw, 854px\" \/><\/figure>\n\n\n\n<p>In this tutorial, you have learned how to use the SQL Server <code>TRY CATCH<\/code> construct to handle exceptions in stored procedures.<\/p>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1899\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/\"\n\t\t\t\tdata-post-title=\"SQL Server TRY CATCH\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1899\"\n\t\t\t\tdata-post-url=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/\"\n\t\t\t\tdata-post-title=\"SQL Server TRY CATCH\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":777,"menu_order":10,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1899","page","type-page","status-publish","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>SQL Server TRY CATCH - Handling Exception in Stored Procedures<\/title>\n<meta name=\"description\" content=\"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"SQL Server TRY CATCH - Handling Exception in Stored Procedures\" \/>\n<meta property=\"og:description\" content=\"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/\" \/>\n<meta property=\"og:site_name\" content=\"SQL Server Tutorial\" \/>\n<meta property=\"article:modified_time\" content=\"2020-04-11T13:12:14+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/\",\"url\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/\",\"name\":\"SQL Server TRY CATCH - Handling Exception in Stored Procedures\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/wp-content\\\/uploads\\\/SQL-Server-TRY-CATCH-Example.png\",\"datePublished\":\"2019-05-01T01:32:21+00:00\",\"dateModified\":\"2020-04-11T13:12:14+00:00\",\"description\":\"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/wp-content\\\/uploads\\\/SQL-Server-TRY-CATCH-Example.png\",\"contentUrl\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/wp-content\\\/uploads\\\/SQL-Server-TRY-CATCH-Example.png\",\"width\":538,\"height\":38,\"caption\":\"SQL Server TRY CATCH Example\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/sql-server-try-catch\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"SQL Server Stored Procedures\",\"item\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/sql-server-stored-procedures\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"SQL Server TRY CATCH\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/#website\",\"url\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/\",\"name\":\"SQL Server Tutorial\",\"description\":\"The Practical SQL Server Tutorial\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.sqlservertutorial.net\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"SQL Server TRY CATCH - Handling Exception in Stored Procedures","description":"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/","og_locale":"en_US","og_type":"article","og_title":"SQL Server TRY CATCH - Handling Exception in Stored Procedures","og_description":"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.","og_url":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/","og_site_name":"SQL Server Tutorial","article_modified_time":"2020-04-11T13:12:14+00:00","og_image":[{"url":"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png","type":"","width":"","height":""}],"twitter_card":"summary_large_image","twitter_misc":{"Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/","url":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/","name":"SQL Server TRY CATCH - Handling Exception in Stored Procedures","isPartOf":{"@id":"https:\/\/www.sqlservertutorial.net\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/#primaryimage"},"image":{"@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/#primaryimage"},"thumbnailUrl":"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png","datePublished":"2019-05-01T01:32:21+00:00","dateModified":"2020-04-11T13:12:14+00:00","description":"In this tutorial, you will learn how to use the SQL Server TRY CATCH construct to handle exceptions in stored procedures.","breadcrumb":{"@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/#primaryimage","url":"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png","contentUrl":"https:\/\/www.sqlservertutorial.net\/wp-content\/uploads\/SQL-Server-TRY-CATCH-Example.png","width":538,"height":38,"caption":"SQL Server TRY CATCH Example"},{"@type":"BreadcrumbList","@id":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/sql-server-try-catch\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.sqlservertutorial.net\/"},{"@type":"ListItem","position":2,"name":"SQL Server Stored Procedures","item":"https:\/\/www.sqlservertutorial.net\/sql-server-stored-procedures\/"},{"@type":"ListItem","position":3,"name":"SQL Server TRY CATCH"}]},{"@type":"WebSite","@id":"https:\/\/www.sqlservertutorial.net\/#website","url":"https:\/\/www.sqlservertutorial.net\/","name":"SQL Server Tutorial","description":"The Practical SQL Server Tutorial","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.sqlservertutorial.net\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/1899","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/comments?post=1899"}],"version-history":[{"count":0,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/1899\/revisions"}],"up":[{"embeddable":true,"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/pages\/777"}],"wp:attachment":[{"href":"https:\/\/www.sqlservertutorial.net\/wp-json\/wp\/v2\/media?parent=1899"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}