Solved

How to use RaiseError in my stored proc

Posted on 2014-12-12
6
83 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 47

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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

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 47

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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
sql Total query 2 26
SQL Pivot Rows To Columns 10 53
SQL Server 2012 r2 Make faster Temp Table 17 103
Is there any way to convert exponential value to number in sql server 5 38
In this article I will describe the Copy Database Wizard 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.
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…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

774 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