RSS

How to write (TRY … CATCH) in MS SQL Server .. ??

13 Oct

In this topic we will learn how can we handle exception in MS SQL Server. If you tried to execute the following the next T-SQL command:-

USE [pubs]

SELECT * FROM [Companies]

Here, as you know the pubs database did not has the table named (), and after trying to execute this T-SQL command the following error will be raised:

Msg 208, Level 16, State 1, Line 2
Invalid object name ‘Companies’.

What will you do if you want to handle the previous error and do something else such as displaying a message that inform user that there is something is incorrect or execute another T-SQL command … etc. Try it:-

BEGIN TRY

INSERT INTO [Users]
(UserID, UserName, Password, EMail)
VALUES
(7, ‘Ahmed’, ‘p@ssw0rd’, ‘AhmedNegm@WindowsLive.com’)

END TRY

BEGIN CATCH

PRINT ‘There is something incorrect in your T-SQL executed command.’

END CATCH

 
2 Comments

Posted by on October 13, 2011 in MS SQL Server

 

Tags: , , , ,

2 responses to “How to write (TRY … CATCH) in MS SQL Server .. ??

  1. Mohamed Fawzy

    October 23, 2011 at 5:12 PM

    ربنا يزيدك علم وتنفع بيه الناس اكتر واكتر

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: