Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to use RaiseError in my stored proc

Posted on 2014-12-12
6
Medium Priority
?
96 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
[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
6 Comments
 
LVL 52

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 35

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 1000 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
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

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 52

Assisted Solution

by:Vitor Montalvão
Vitor Montalvão earned 1000 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

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

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

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
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 …
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

688 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