Error handling in SQL Server 

SQL Server does error handling with the TRY and CATCH statements. The syntax for this is shown in the following code: 

BEGIN TRY  
--sql statements
END TRY
BEGIN CATCH
--sql statements
END CATCH

Anything you want to execute goes in the TRY statement, and if there is an error, the CATCH statement will run. If there is no error, the TRY statements are successfully executed, and the CATCH statement is never used.

The following query will try to insert values into the allstarfull table using the TRY and CATCH statements: 

DECLARE @inplayerid varchar(9) = 'aaronha01';
DECLARE @inyearid smallint = 1958;
DECLARE @ingamenum smallint = 0;
BEGIN TRY
INSERT INTO allstarfull
(playerid, yearid, gamenum)
VALUES
(@inplayerid, @inyearid, @ingamenum);
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

You will receive an error with those variables set as-is because there is a primary key violation, as shown in the following screenshot:

To learn more about the TRY and CATCH statements in SQL Server, take a look at the Further reading section. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.91