Solved

How to use RaiseError in my stored proc

Posted on 2014-12-12
6
80 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 45

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 32

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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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 45

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

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
This video discusses moving either the default database or any database to a new volume.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

705 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

20 Experts available now in Live!

Get 1:1 Help Now