Solved

Catch error in insert select

Posted on 2015-02-06
4
231 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
  • 2
  • 2
4 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 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 65

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

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
MS SQL Backup 24 70
Sql query for filter 12 22
Table create permissions on SQL Server 2005 9 15
Update in Sql 7 0
In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

760 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now