?
Solved

Catch error in insert select

Posted on 2015-02-06
4
Medium Priority
?
248 Views
Last Modified: 2015-02-06
I want to perform select insert. If error on inserting or update, it should roll back and return "Error message" if not it should return "Successful". Is this correct? I am not sure how to do this.


begin transaction

insert into table_1
(date, name, username)
select date, name, username
from table_2

update table ...etc

if @@error <> 0
begin
    if @@trancount > 0
        rollback
    return
end

commit
0
Comment
Question by:VBdotnet2005
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 66

Accepted Solution

by:
Jim Horn earned 2000 total points
ID: 40594834
BEGIN TRY
   BEGIN TRAN tr

   -- do your stuff here

   -- If code execution makes it here, good to go.
   COMMIT TRAN tr
END TRY

BEGIN CATCH
   -- If code execution makes it here then an error occured.   Rollback everything that happened up to the BEGIN TRANS.
   ROLLBACK TRAN tr
END CATCH
0
 

Author Comment

by:VBdotnet2005
ID: 40594838
Hi Jim,

Can it be returned with a message? If errors, it return "my error message", if no error, it should return " my message".
0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 40594848
Sure, right before the ROLLBACK, something like...

SELECT 'An error occured' + ERROR_PROCEDURE() as message, 
   ERROR_NUMBER() as number, 
   ERROR_MESSAGE() as message

Open in new window

0
 

Author Comment

by:VBdotnet2005
ID: 40594872
Thank you very much Jim
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question