Solved

How to use RaiseError in my stored proc

Posted on 2014-12-12
6
82 Views
Last Modified: 2014-12-17
I am running a backup and restore script in a stored proc, which is run on a sql agent job. If the backup or the restore fails, the sql agent step still shows completed successfully. How can I use RaiseError in my stored proc script so the sql agent step does show failed if backup or restore failed.

Here is my Sproc script:

USE [My_data]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[bckup_restr_my_db]
as

--archive   
declare @exitcode integer                      
declare @sqlerrorcode integer                                                              
declare @dt varchar(25)                      
declare @exeString varchar(500)    
declare @exeString2 varchar(500)      
        
                    
                      
select @dt = replace(replace(convert(varchar(25), getdate()), ' ', '_'), ':', '')                      
set @exeString = N'-SQL "BACKUP DATABASE [My_data] TO DISK = 
''E:\MSSQL\My_data_' + @dt + '.sqb'' WITH ERASEFILES = 2, DISKRETRYINTERVAL = 30, DISKRETRYCOUNT = 10, COMPRESSION = 4, THREADCOUNT = 7"'  
                      
EXECUTE [MyETLServer].master..sqlbackup @exeString, @exitcode OUTPUT, @sqlerrorcode OUTPUT  

if @exitcode <> 0                       
return 1      


set @exeString2 =  N'-SQL "RESTORE DATABASE [My_data] FROM DISK = ''\\MyETLServer\MSSQL\My_data_' + @dt + '.sqb'' WITH RECOVERY, DISCONNECT_EXISTING,  MOVE ''My_data'' TO ''Y:\MSSQL-G1-Data\Data\My_data.mdf'', MOVE ''My_data_log'' TO ''Y:\MSSQL-G1-Logs\Logfiles\My_data_log.ldf'', REPLACE, ORPHAN_CHECK"'
EXECUTE [MyProdServer].master..sqlbackup @exeString2, @exitcode OUTPUT, @sqlerrorcode OUTPUT 

if @exitcode <> 0                       
return 1     

Open in new window

0
Comment
Question by:patd1
6 Comments
 
LVL 46

Expert Comment

by:Vitor Montalvão
ID: 40496242
Before the Return 1 statement add a Raise Error command. Example:
RAISERROR ('Error during Backup & Restore procedure.', -- Error message text.
               16, -- Severity.
               1 -- State.
               )

Open in new window

0
 
LVL 33

Expert Comment

by:ste5an
ID: 40496297
Cause you have no error handling and are always returning 1 as result code..
0
 
LVL 23

Assisted Solution

by:Racim BOUDJAKDJI
Racim BOUDJAKDJI earned 250 total points
ID: 40496299
Just to get you started...Note that sp_msforeachdb is not supported but is fine to use in BACKUP process.

exec sp_msforeachdb '
if lower(''?'') not in (''tempdb'')
begin
	backup database [?] to disk= ''C:\[?]_.BAK'';

	if @@error  <> 0
	begin
		raiserror (''Failure of [?] backup.'', 16, 1)
	end
end'

Open in new window

0
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.

 

Accepted Solution

by:
patd1 earned 0 total points
ID: 40496316
Thanks for your help Vitor Montalvão.

If exitcode <> 0 that means it was error, so I raise error. But why is it not failing as it returns 1?

Please review the code below, if that is what is needed.

if @exitcode <> 0          
            RAISERROR ('Error during Backup & Restore procedure.', -- Error message text.
               16, -- Severity.
               1 -- State.
               ) 
return 1  

Open in new window

0
 
LVL 46

Assisted Solution

by:Vitor Montalvão
Vitor Montalvão earned 250 total points
ID: 40496330
You need a BEGIN END block since there's more than one line of code after the IF:
if @exitcode <> 0          
BEGIN
        RAISERROR ('Error during Backup & Restore procedure.', -- Error message text.
               16, -- Severity.
               1 -- State.
               ) 
     return 1
END  

Open in new window

0
 

Author Closing Comment

by:patd1
ID: 40504389
Thank you.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Calculating Business Hours 19 81
Partially Contained Databases - Connection Strings must be explicit 3 33
Square brackets 4 38
SQL Server - SQL field is defined as text 3 27
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This is a video describing the growing solar energy use in Utah. This is a topic that greatly interests me and so I decided to produce a video about it.
This is a video that shows how the OnPage alerts system integrates into ConnectWise, how a trigger is set, how a page is sent via the trigger, and how the SENT, DELIVERED, READ & REPLIED receipts get entered into the internal tab of the ConnectWise …

919 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

13 Experts available now in Live!

Get 1:1 Help Now