Saturday 30 March 2013

Backup on network Drive with Map Drive


STEP 1:-
-- First Execute this command ---
Exec master.dbo.sp_configure 'show advanced option',1
reconfigure
Exec Master.dbo.SP_configure 'XP_cmdshell',1
reconfigure
--OutPut Like This
--Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
--Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.

-----------------------------BIND DRIVE WITH SYSTEM------------------------------------------------------------------------
STEP 2:-
Exec XP_CMDSHELL 'net use z: \\satan\BACKUP HPDC2011@ /user:satan\ashish'
----outPut Should be like this
--The command completed successfully.
--NULL
--NULL
----------------------VARIFY DRIVE INFO------------------------
STEP 3:-

Exec XP_cmdshell 'dir z:'

--OutPut Like This
-- Volume in drive Z has no label.
-- Volume Serial Number is B481-00AF
--NULL
-- Directory of Z:\
--NULL
--03/29/2013  04:43 AM    <DIR>          .
--03/29/2013  04:43 AM    <DIR>          ..
--03/29/2013  04:43 AM         3,165,696 m.bak
--               1 File(s)      3,165,696 bytes
--               2 Dir(s)  14,739,963,904 bytes free
--NULL

--Exec XP_CMDSHELL 'net use y: \\satan\myfile HPDC2011@ /user:satan\ashish'
---------------------Run BackUp Command--------------
STEP 4:-

Backup database master to disk='\\satan\BACKUP\master.bak'

---Processed 376 pages for database 'master', file 'master' on file 2.
--Processed 3 pages for database 'master', file 'mastlog' on file 2.
--BACKUP DATABASE successfully processed 379 pages in 2.448 seconds (1.206 MB/sec).




Wednesday 20 March 2013

Full Back Up With Understanding of Parameters Like,init,Format,Name,Stat


A simple T-SQL script for full backups
Take a look at Listing 3-8, which shows a script that can be used to take a full backup of the newly populated DatabaseForFullBackups database.
USE master GO BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' WITH FORMAT, INIT, NAME = N'DatabaseForFullBackups-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10 GO
Listing 3-8: Native full backup T-SQL script.
This script may look like it has some extra parameters, compared to the native GUI backup that we did earlier, but this is the scripted output of that same backup, with only the output file name modified, and a few other very minor tweaks. So what do each of these parameters mean?
The meaning of the first line should be fairly obvious; it is instructing SQL Server to perform a full backup of the DatabaseForFullBackups database. This leads into the second line where we have chosen to back up to disk, and given a complete file path to the resulting backup file. The remainder of the parameters are new, so let's go through each one.108 Chapter 3: Full Database Backups
                        FORMAT This option tells SQL Server whether or not to overwrite the media header infor­mation. The FORMAT option will erase any information in a backup set that already exists when the backup is initialized (NOFORMAT will preserve it).
                        INIT By default, when scripting a backup generated by the Backup wizard, this parameter will be set to NOINIT, which lets SQL Server know not to initialize a media set when taking the backup and instead append any new backup data to the existing backup set. However, since we adopt the rule of one backup per backup set, it's useful to use INIT instead, to make sure that, if a command gets run twice, we overwrite the existing set and still end up with only one backup in the set.
                        NAME The NAME parameter is simply used to identify the backup set. If it is not supplied, the set will not record a name.
                        SKIP Using the SKIP parameter will cause SQL Server to skip the expiration check that it normally does on the backup set. It doesn't care if any backups existing in the backup set have been marked for availability to be overwritten.
                        NOREWIND This parameter will cause SQL Server to keep a tape device open and ready for use when the backup operation is complete. This is a performance boost to users of tape drives since the tape is already at the next writing point instead of having to search for the correct position. This is obviously a tape-only option.
                NOUNLOAD When backing up to a tape drive, this parameter instructs SQL Server not to unload the tape from the drive when the backup operation is completed.
                        STATS This option may prove useful to you when performing query-based backups. The STATS parameter defines the time intervals on which SQL Server should update the "backup progress" messages. For example, using stats=10 will cause SQL Server to send a status message to the query output for each 10 percent of the backup completion.

As noted, if we wished to overwrite an existing backup set, we'd want to specify the INIT parameter but, beyond that, none of these secondary parameters, including the backup set NAME descriptor, are required. As such, we can actually use a much simplified BACKUP command, as shown in Listing 3-9.
BACKUP DATABASE [DatabaseForFullBackups] TO DISK = N'C:\SQLBackups\Chapter3\DatabaseForFullBackups_Full_Native_2.bak' GO
Listing 3-9: Slimmed-down native T-SQL backup code.
Go ahead and start Management Studio and connect to your test server. Once you have connected, open a new query

Tuesday 19 March 2013

Get last backup details of all databases in a server


This stored procedure give you the information about latest backups happened on all databases in a server.
This SP works for SQL server 2005 and up.
Create Proc sp_BackupDetails
AS
DECLARE @BackupDetails table
([Server Name] nvarchar(500),
[Database Name] nvarchar(500),
[Last Full Backup] nvarchar(500),
[Last Differential Backup] nvarchar(500),
[Last Log Backup] nvarchar(500),
[Last File or filegroup Backup] nvarchar(500),
[Last Differential file Backup] nvarchar(500),
[Last Partial Backup] nvarchar(500),
[Last Differential Partial Backup] nvarchar(500)
)

DECLARE @DBName nvarchar(500)
Declare DBName Cursor for
Select name from sys.databases
Open DBName
Fetch Next from DBName into @DBName
While @@fetch_status = 0
BEGIN
Insert into @BackupDetails
select @@ServerName as [Server Name]
       ,SDB.name AS [Database Name]
       ,(select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='D') AS [Last Full Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='I') AS [Last Differential Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='L') AS [Last Log Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='F') AS [Last File or filegroup Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='G') AS [Last Differential file Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='P') AS [Last Partial Backup]
       ,(Select COALESCE(Convert(nvarchar(20), MAX(backup_finish_date), 100),'NA') frommsdb..backupset where database_name=@DBName and type='Q') AS [Last Differential Partial Backup]
from sys.databases SDB
where SDB.name =@DBName
Fetch Next from DBName into @DBName
END
Close DBName
DEALLOCATE DBName

Select * from @BackupDetails
GO

Usage:
Exec sp_BackupDetails
go

Out Put After Execute 

Server Name Database Name Last Full Backup Last Differential Backup Last Log Backup Last File or filegroup Backup Last Differential file Backup Last Partial Backup Last Differential Partial Backup
GHOST-PC\INS10 master Mar 19 2013 12:00PM NA NA NA NA NA NA
GHOST-PC\INS10 tempdb NA NA NA NA NA NA NA
GHOST-PC\INS10 model NA NA NA NA NA NA NA
GHOST-PC\INS10 msdb NA NA NA NA NA NA NA
GHOST-PC\INS10 demo Mar 19 2013 12:13PM NA NA NA NA NA NA
GHOST-PC\INS10 demo1 Mar 19 2013 12:14PM NA NA NA NA NA NA

RESTORE DATABASE ON ANOTHER LOCATION WITH SQL COMMAND



-CHECK .MDF AND .LDF LOGICAL NAME IF YOU HAVE A .BAK DATABASE BACKUP FILE-
 Restore filelistonly from disk='E:\DEMO1.bak'


 CREATE DATABASE DEMO1---CREATE A DATABASE 

   SP_HELPDB'DEMO1'

RESTORE DATABASE DEMO1 FROM disk='E:\Demo1.bak'
WITH MOVE 'DEMO1' TO 'E:\MOVE\Demo1.MDF',
MOVE 'demo1_log' TO 'E:\MOVE\demo1_log.LDF',REPLACE 

Monday 18 March 2013

Moving System Databases One Place To Another


Best-Practice Of Moving Master and Resource Databse:
Notes: -
1.    The procedures in this topic require the logical name of the database files. To obtain the name, query the name column in the sys.master_files catalog view.
2.    Before moving the system databases, ensure to have full database backup of all system databases (except Resource database).
3.    Also, ensure to have offline backup (mdf & ldf files) of all system databases including Resource database.
4.    Carry out the activity successfully on the UAT server before proceeding with the same on the Production servers.

Moving the master and Resource Databases
The Resource database depends on the location of the master database. The Resource data and log files must reside together and must be in the same location as the master data file (master.mdf). Therefore, if you move the master database, you must also move the Resource database to the same location as the master data file. Do not put the Resource database in either compressed or encrypted NTFS file system folders. Doing so will hinder performance and prevent upgrades.
To move the master and Resource databases, follow these steps.
  1. From the Start menu, point to All Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
  2. In the SQL Server 2005 Services node, right-click the instance of SQL Server (for example, SQL Server (MSSQLSERVER)) and choose Properties.
  3. In the SQL Server (instance_name) Properties dialog box, click the Advanced tab.
  4. Edit the Startup Parameters values to point to the planned location for the master database data and log files, and click OK. Moving the error log file is optional.
    The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files.
-dC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\master.mdf;
-eC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG;
-lC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\mastlog.ldf
If the planned relocation for the master data and log files is E:\SQLData, the parameter values would be changed as follows:
-dE:\SQLData\master.mdf;
-eC:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG;
-lE:\SQLData\mastlog.ldf
  1. Stop the instance of SQL Server by right-clicking the instance name and choosing Stop.
  2. Move the master.mdf and mastlog.ldf files to the new location.
  3. Start the instance of SQL Server in master-only recovery mode by entering one of the following commands at the command prompt. The parameters specified in these commands are case sensitive. The commands fail when the parameters are not specified as shown.
·         For the default (MSSQLSERVER) instance, run the following command:
NET START MSSQLSERVER /f /T3608
·         For a named instance, run the following command:
NET START MSSQL$instancename /f /T3608

  1. Using sqlcmd commands or SQL Server Management Studio, run the following statements. Change the FILENAME path to match the new location of the master data file. Do not change the name of the database or the file names.
ALTER DATABASE mssqlsystemresource 
MODIFY FILE (NAME=data, FILENAME= 'new_path_of_master\mssqlsystemresource.mdf');
GO
ALTER DATABASE mssqlsystemresource 
MODIFY FILE (NAME=log, FILENAME= 'new_path_of_master\mssqlsystemresource.ldf');
GO
  1. Move the mssqlsystemresource.mdf and mssqlsystemresource.ldf files to the new location.
  2. Set the Resource database to read-only by running the following statement:
ALTER DATABASE mssqlsystemresource SET READ_ONLY;
  1. Exit the sqlcmd utility or SQL Server Management Studio.
  2. Stop the instance of SQL Server.
  3. Restart the instance of SQL Server.
  4. Verify the file change for the master database by running the following query. The Resource database metadata cannot be viewed by using the system catalog views or system tables.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID ('master');
GO



Moving model and msdb databases
Moving of model and msdb databases also follow the similar procedure as moving the tempdb database but with some additional steps.
Since these are also system databases, unfortunately we cannot move them just by detach and attach process, as we cannot attach or detach a system database.

Moving model database:
1.            First get the list of model database files by using this query
select name,physical_name from sys.master_files whereDB_NAME(database_id)='model'  
2.            Then for each model database file that you need to move, execute statements like below
Alter Database model modify
file (NAME = 'modeldev' ,
FILENAME = 'Drive:\Path\model.mdf') -- Mention the new location

Alter Database model modify
file (NAME = 'modellog' ,
FILENAME = 'Drive:\Path\modellog.ldf') -- Mention the new location
3.            Stop SQL Services
4.            Move the files manually to the new location
5.            Start SQL Services
6.            Verify the new Location
select name,physical_name from sys.master_files whereDB_NAME(database_id)='model'

Moving msdb database
:
1.            First get the list of msdb files by using this query
select name,physical_name from sys.master_files whereDB_NAME(database_id)='msdb'  
2.            Then for each msdb database file that you need to move, execute statements like below
Alter Database msdb modify
file (NAME = 'MSDBData' ,
FILENAME = 'Drive:\Path\MSDBData.mdf') -- Mention the new location

Alter Database msdb modify
file (NAME = 'MSDBLog' ,
FILENAME = 'Drive:\Path\MSDBLog.ldf') -- Mention the new location
3.            Stop SQL Services
4.            Move the files manually to the new location
5.            Start SQL Services
6.            Verify the new Location
select name,physical_name from sys.master_files whereDB_NAME(database_id)='msdb'
If the SQL Server Instance is configured with Database Mail option, then after the msdb movement you will have to verify that the database mail is working fine by sending a test email.


DEMO :-

sp_helpdb 'master'
ALTER DATABASE mssqlsystemresource
MODIFY FILE (NAME=data, FILENAME= 'D:\prod\mssqlsystemresource.mdf');
GO
ALTER DATABASE mssqlsystemresource
MODIFY FILE (NAME=log, FILENAME= 'D:\prod\mssqlsystemresource.ldf');
GO
--Move the mssqlsystemresource.mdf and mssqlsystemresource.ldf files to the new location.
--Set the Resource database to read-only by running the following statement:
ALTER DATABASE mssqlsystemresource SET READ_ONLY;


sp_helpdb 'model'

Alter DATABASE MODEL MODIFY FILE
( NAME=modeldev,FILENAME='D:\prod\model.MDF')
GO
Alter DATABASE MODEL MODIFY FILE
( NAME=modellog,FILENAME='D:\prod\modellog.LDF')
GO

sp_helpdb 'MSDB'

Alter DATABASE MSDB MODIFY FILE
( NAME=MSDBData,FILENAME='D:\prod\MSDBData.MDF')
GO

Alter DATABASE MSDB MODIFY FILE
( NAME=MSDBLog,FILENAME='D:\prod\MSDBLog.LDF')
GO

sp_helpdb 'TEMPDB'

Alter DATABASE TEMPDB MODIFY FILE
( NAME=tempdev,FILENAME='D:\prod\tempdb.MDF')
GO

Alter DATABASE TEMPDB MODIFY FILE
( NAME=templog,FILENAME='D:\prod\templog.LDF')
GO