Solved

Catch error in insert select

Posted on 2015-02-06
4
236 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
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 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 UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

856 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