Friday, August 29, 2014

Database Backup Script...

!!!!!!! - Wish you all a very Happy Ganesh Chaturthi - !!!!!!!

(Couple of new things happened in last few weeks. Started working with new some onshore Clients where I’ll get exposed to some new technology to learn along with SQL Server. Also my favorite Series 24 Season 5, where Jack Bauer is back to find the reason behind assassination of former President David Palmer and today is Ganesh Chaturthi as well.)

Requirement: One of my client asked to us to design a script which should take backup of all Databases including system DB, Verify those Backups from corruption & also should clean up old backups depending upon retention period.

Solution: Below you can find the script which satisfies the above requirement. This code is compatible from 2005 on wards.

Following is the detailed description of the code:

Parameters:

*@Directory => Mention the Backup location to take. It is compulsory.
*@No_of_hours => Specify how much older backup you want to delete. It is again compulsory.
@BackupType => Type of Backup Full (F), Differential (D) and Log (L) Backup. By default it will take Full Backup.
 @Verify => It will verify the Backup against corruption. By default it will not verify the backup [Y => Yes; N => No].

Example how the code will work:

E.g.  Suppose you pass SP_Backup ‘D:\Backup\’, 25, ‘D’,’Y’

1. Identify the list of Databases which Differential Backup needs to be done.
2. Databases backup will be done on D:\Backup\*.diff drive.
3. It will simultaneously verify the Backups; as the parameter passed is Y.
4.  Finally; it will delete the 25 Hours Backup Files from the same directory.


USE [master]
GO
/****** Object:  StoredProcedure [dbo].[SP_Backup]    Script Date: 8/28/2014 12:53:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[SP_Backup_ALL] --SP_Backup_ALL 'C:\Backup\',1

@Directory NVARCHAR(256), -- Mention Path to take the Backup [E.g. C:\Backup\]
@No_of_hours INT, -- Specify no of hours to clean old backups [E.g. 5 means it will delete 5 Hours old Backup]
@BackupTYpe NVARCHAR(10) ='F', -- Specify Backup Type; By default it will take "Full" Backup [F => Full; D => Differential; L => Log]
@Verify NVARCHAR(256)='N' -- Specify Verify Type; By default it will not verify the backup [Y => Yes; N => No]
As 
Begin

Declare @Name NVARCHAR(100) -- Database Name  
Declare @FileDate NVARCHAR(100) -- Used for file name
Declare @FileName NVARCHAR(256) -- Filename for Full & Diff backup  
Declare @FileName_Log NVARCHAR(256) -- Filename for Log backup 
Declare @DeleteDate NVARCHAR(100)
Declare @DeleteDateTime DATETIME

Set @FileDate = CONVERT(VARCHAR(20),GETDATE(),112) + REPLACE(CONVERT(VARCHAR(20),GETDATE(),108),':','')
Set @DeleteDateTime = DateAdd(hh, -@No_of_hours, GetDate())
Set @DeleteDate = (Select Replace(Convert(nvarchar, @DeleteDateTime, 111), '/', '-') + 'T' + Convert(nvarchar, @DeleteDateTime, 108))

/***************Start Full Backup*********************/

IF @BackupTYpe='F'  
  BEGIN
  DECLARE db_cursor CURSOR FOR  
SELECT name
FROM master.sys.databases 
WHERE state_desc='ONLINE' and name NOT IN ('tempdb')   -- Exclude these databases (Specify the list of databases which you want to exclude from backup)

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN   
SET @fileName = @Directory + @name + '_' + @fileDate + '.bak'  
BACKUP DATABASE @name TO DISK = @fileName with stats=25  
  
/***************Verify the backup*********************/
IF @Verify = 'Y'
BEGIN
Restore verifyonly from disk = @fileName
END  
FETCH NEXT FROM db_cursor INTO @name   
END  
 
CLOSE db_cursor   
DEALLOCATE db_cursor
END
ELSE

/***************Start Differential Backup*********************/

IF @BackupTYpe='D'  
  BEGIN

DECLARE db_cursor CURSOR FOR  

SELECT a.name
FROM master.sys.databases a
LEFT OUTER JOIN msdb..backupset b ON a.name = b.database_name 
where b.type='D' and a.name <> 'master'and a.state_desc='ONLINE'
GROUP BY a.name, b.type 
ORDER BY a.name, b.type

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN   
SET @fileName = @Directory + @name + '_' + @fileDate + '.diff'  
--print @fileName
BACKUP DATABASE @name TO DISK = @fileName with Differential,stats=25 
  
/***************Verify the backup*********************/
IF @Verify = 'Y'
BEGIN
Restore verifyonly from disk = @fileName
END  
FETCH NEXT FROM db_cursor INTO @name   
END  
 
CLOSE db_cursor   
DEALLOCATE db_cursor
END

/***************Start Log Backup*********************/
ELSE
IF @BackupTYpe='L'  
  BEGIN

DECLARE db_cursor CURSOR FOR  

/******* DB's with Simple Recovery Model  & DB's with no Full Backup will be skip from Log Backup *******/

SELECT a.name
FROM master.sys.databases a
LEFT OUTER JOIN msdb..backupset b ON a.name = b.database_name 
where a.recovery_model_desc <> 'SIMPLE' and b.type='D'and a.state_desc='ONLINE'
GROUP BY a.name, b.type 
ORDER BY a.name, b.type

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @name   

WHILE @@FETCH_STATUS = 0   
BEGIN   

SET @fileName_Log = @Directory + @name + '_' + @fileDate + '.trn' 
--print @fileName_Log
BACKUP log @name TO DISK = @fileName_Log  with stats=25
  
/***************Verify the backup*********************/
IF @Verify = 'Y'
BEGIN
Restore verifyonly from disk = @fileName_Log
END  
FETCH NEXT FROM db_cursor INTO @name   
END  
 
CLOSE db_cursor   
DEALLOCATE db_cursor
END

/*********** Start Deletion of OLD Backups *****************/

IF @BackupTYpe = 'F'
BEGIN 
EXECUTE master.dbo.xp_delete_file 0,@Directory,N'bak',@DeleteDate,1 -- It will delete the "Full" Backup
END
ELSE 

IF @BackupTYpe = 'D'
BEGIN 
EXECUTE master.dbo.xp_delete_file 0,@Directory,N'diff',@DeleteDate,1 -- It will delete the "Differential" Backup
END
ELSE 
BEGIN 
EXECUTE master.dbo.xp_delete_file 0,@Directory,N'trn',@DeleteDate,1 -- It will delete the "Log" Backup
END

END
GO


Let me know if any concerns.

Ganpati Bappa Moriya!!!!!


Saturday, August 16, 2014

Farewell Mail....

Dear Team,

As most of you might know that today is my last working day. It’s been total 3.4 years in this organization now. Before leaving I would like to grab your couple of minutes to share my feelings.

I would like to take the opportunity to thanks all my colleagues who have really made the journey so memorable.
Firstly, this could never been possible without Prashant Sir & Lakshmi Mam (Interviewer) who has given break to my career.

Time spend with the batch will always be most memorable and ever green forever. Special thanks to Liz Mam for assigning me such a wonderful sites after completion of training.

It was very good learning experience with Abhijit K and Abhijit S under whom I spend most of the time. Also personally I would like to thanks Kalim K, Rohit I, Kunal A, Ritesh M, Sushil D, Jabeen (Ma)m, Chandan R, Amod B, Anirudh K, Vineet N, Rahul J, Subodh, Nilkanth D, Kishore G, Younis D, Rohit N, Mithun P, Sandeep J, Akilesh H, Muthu K, Deepali G and Palksha for helping me to grow.

As I’m very much emotionally attached to our company, so I would never say good bye. We might definitely meet at some point in life again.

Dear SQL Team,

Feel free to get in touch with me for any technical assistance. I would be glad to be of any help.

Here are my personal contact details:

Call me on: 08452910970
Drop me on ID: vikasbsahu@gmail.com

--
Thanks & Regards,
Vikas Sahu

Sunday, July 20, 2014

How to Restore Master Database?

Hi Friends,

(One of my favorite American Series is 24. Recently I have completed with Season 4 of this series. The seasons story revolves around how Jack Bauer prevents the nuke war on US Soil.)

After getting start with my first post About Linked Server which was the first part of three part series. I like to introduce here my next post in which I want to share one of my personal experiences with you all.

So the question here stands is: How can we restore Master Database (MDB)?

Answer:
  1.  MDB is one of the most important System DB. This DB holds the responsibility to start the SQL Server Instance.
  2. As we know MDB is the heart of SQL Server in which all the logins, DB Path, LS information are stored in this DB itself.
  3. So it becomes necessary to backup MDB on regular basis.

Most of the timings restoring MDB come into picture in case of disaster only. To Restore the MDB we need to follow the below steps:
  1. Note down the path of the latest MDB backup file
  2. Take the Server into Single user mode
  3. Connect the SQL Server
  4.  Restore the MDB with replace
      Kindly refer the msdn for more details.


Thanks,
Vikas Sahu


Saturday, July 5, 2014

About Linked Server - Part 1

Dear Friends,

Thanks for your lovely wishes for my first post. This will really help me and also encourage keeping on updating my blog with new posts.

Last weekend had a beautiful family trip to Matheran.
(It was my fourth overnight picnic to Matheran. Here we can see some ancients British Style Bungalow (Haunted too) surrounded between the trees. Cool breeze especially during evening will refreshes the mind.
Despite around 38 spots, my personal favorite spot would be Malang Point and Sunset Point as we would be getting a good view from these points. 
Guys even though best time to visit, would be after rainy season, but it’s worth to visit the place any time) 

I like to introduce our maiden topic with - About Linked Server [LS]. It will be a three part series and will be covered in next few weeks. 
Also would like to keep all my posts as simple as I can.
  •     Introduction
  •     How to configuration LS
  •     Troubleshooting
Introduction to Linked Server [LS]:
Linked Server [LS] is a feature in MS SQL Server which needs to be configured, if we want to communicate (through query) with the outside world.

Once LS is configured, it can be used to exchange information using different data sources. This data sources can be anything such as MS SQL, Oracle, DB2, Progress, etc... Databases.
We can check out the list of LS from the following path. 
SSMS >>> Server Node >>> Server Objects >>> Linked Servers >>> (Here you can see list of LS present)



Following are the two ways to call LS:
  • Four-Part Naming
  • Open Query
Conventions for calling the LS are as follow:
  1. Four-Part Naming: Select * from [LS_Name]. [DB_Name]. [Schema_Name].[Table_Name]
  2. Open Query: Select * from OPENQUERY (LS_Name, (select * from [Table_Name]))
In next series, we will be learning how to configure the LS. Also click here for more information on Linked Server available on msdn site.

Lets windup here as its 8.20 AM Friday, will get ready and leave for office. Will review the content and publish the post by evening.
Stay tuned for more update. Suggestions are always welcome. Take care Friends. Bye.

Thanks,
Vikas Sahu