Category: Backup & Recovery

  • Scripts which make you Database Hero


    — Create databsae SQLDBPool
    CREATE DATABASE [sqldbpool] ON PRIMARY
    ( NAME = N’sqldbpool’, FILENAME = N’C:\sqldbpool.mdf’ , SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
    LOG ON
    ( NAME = N’sqldbpool_log’, FILENAME = N’C:\sqldbpool_log.ldf’ , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
    COLLATE SQL_Latin1_General_CP1_CI_AS
    GO

    –Script to create schema
    USE [sqldbpool]
    GO
    CREATE SCHEMA [mySQLDBPool] AUTHORIZATION [dbo]

    — Script to create table with constraints
    create table mySQLDBPool.Emp
    (
    EmpID int Primary key identity(100,1),
    EmpName Varchar(20) Constraint UK1 Unique,
    DOB datetime Not Null,
    JoinDate datetime default getdate(),
    Age int Constraint Ck1 Check (Age > 18)
    )

    — Script to change the recovery model of the databsae
    USE [master]
    GO
    ALTER DATABASE [SQLDBPool] SET RECOVERY FULL WITH NO_WAIT
    GO

    ALTER DATABASE [SQLDBPool] SET RECOVERY FULL
    GO

    — Script to take the full backup of database
    BACKUP DATABASE [SQLDBPool] TO DISK = N’D:\SQLDBPool.bak’
    WITH NOFORMAT, INIT, NAME = N’SQLDBPool-Full Database Backup’,
    NOREWIND, SKIP, NOUNLOAD, STATS = 10
    GO

    –Script to take the Differential Database backup
    BACKUP DATABASE [SQLDBPool] TO DISK = N’D:\SQLDBPool.diff.bak’
    WITH DIFFERENTIAL , NOFORMAT, INIT, NAME = N’SQLDBPool-Diff Backup’,
    NOREWIND, SKIP, NOUNLOAD, STATS = 10
    GO

    –Script to take the Transaction Log backup that truncates the log
    BACKUP LOG [SQLDBPool] TO DISK = N’D:\SQLDBPoolTlog.trn’
    WITH NOFORMAT, INIT, NAME = N’SQLDBPool-Transaction Log Backup’,SKIP, NOREWIND, NOUNLOAD, STATS = 10
    GO

    — Backup the tail of the log (not normal procedure)
    BACKUP LOG [SQLDBPool] TO DISK = N’D:\SQLDBPoolLog.tailLog.trn’
    WITH NO_TRUNCATE , NOFORMAT, INIT, NAME = N’SQLDBPool-Transaction Log Backup’,NOREWIND,SKIP, NOUNLOAD, NORECOVERY , STATS = 10
    GO

    — Script to Get the backup file properties
    RESTORE FILELISTONLY FROM DISK = ‘D:\SQLDBPool.bak’

    — Script to Restore Full Database Backup
    RESTORE DATABASE [SQLDBPool1] FROM DISK = N’D:\SQLDBPool.bak’
    WITH FILE = 1, MOVE N’sqldbpool’ TO N’D:\SQLDBPooldata.mdf’,
    MOVE N’sqldbpool_log’ TO N’D:\SQLDBPoollog_1.ldf’,
    NOUNLOAD, STATS = 10
    GO

    — Script to delete the backup history of the specific databsae
    EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N’SQLDBPool1′
    GO

    — Full restore with no recovery (status will be Restoring)
    RESTORE DATABASE [SQLDBPool1] FROM DISK = N’D:\SQLDBPool.bak’
    WITH FILE = 1, MOVE N’SQLDBPool’ TO N’D:\SQLDBPooldata.mdf’,
    MOVE N’SQLDBPool_Log’ TO N’D:\SQLDBPoolLog_1.ldf’,
    NORECOVERY, NOUNLOAD, STATS = 10
    GO

    — Restore transaction log with recovery
    RESTORE LOG [SQLDBPool1] FROM DISK = N’D:\SQLDBPoolLog.trn’
    WITH FILE = 1, NOUNLOAD, RECOVERY STATS = 10
    GO

    –Script to bring the database online without restoring log backup
    restore database sqldbpool with recovery

    –Script to detach database
    USE [master]
    GO
    EXEC master.dbo.sp_detach_db @dbname = N’SQLDBPool’
    GO

    — Script to get the database information
    sp_helpdb ‘SQLDBPOOL’

    –to Attach database
    USE [master]
    GO

    CREATE DATABASE [SQLDBPool1] ON
    ( FILENAME = N’C:\SQLDBPool.mdf’ ),
    ( FILENAME = N’C:\SQLDBPool_Log.ldf’ )
    FOR ATTACH
    GO

    USE SQLDBPool
    GO

    — Get Fragmentation info for each non heap table in SQLDBPool database
    — Avg frag.in percent is External Fragmentation (above 10% is bad)
    — Avg page space used in percent is Internal Fragmention (below 75% is bad)

    SELECT OBJECT_NAME(dt.object_id) AS ‘Table Name’ , si.name AS ‘Index Name’,
    dt.avg_fragmentation_in_percent, dt.avg_page_space_used_in_percent
    FROM
    (SELECT object_id, index_id, avg_fragmentation_in_percent, avg_page_space_used_in_percent
    FROM sys.dm_db_index_physical_stats (DB_ID(‘SQLDBPool’), NULL, NULL, NULL, ‘DETAILED’)
    WHERE index_id <> 0) AS dt
    INNER JOIN sys.indexes AS si
    ON si.object_id = dt.object_id
    AND si.index_id = dt.index_id
    ORDER BY OBJECT_NAME(dt.object_id)

    — Script to Get Fragmention information for a single table
    SELECT TableName = object_name(object_id), database_id, index_id, index_type_desc, avg_fragmentation_in_percent, fragment_count, page_count
    FROM sys.dm_db_index_physical_stats (DB_ID(N’SQLDBPool’), OBJECT_ID(N’mySQLDBPool.Emp’), NULL, NULL , ‘LIMITED’);

    –script to get the index information
    exec sp_helpindex [mySQLDBPool.Emp]

    –Script to Reorganize an index
    ALTER INDEX PK_ProductPhoto_ProductPhotoID ON Production.ProductPhoto
    REORGANIZE
    GO

    — Rebuild an index (offline mode)
    ALTER INDEX ALL ON Production.Product
    REBUILD WITH (FILLFACTOR = 80, SORT_IN_TEMPDB = ON,STATISTICS_NORECOMPUTE = ON);

    –Script to find which columns don’t have statistics
    SELECT c.name AS ‘Column Name’
    FROM sys.columns AS c
    LEFT OUTER JOIN sys.stats_columns AS sc
    ON sc.[object_id] = c.[object_id]
    AND sc.column_id = c.column_id
    WHERE c.[object_id] = OBJECT_ID(‘mySQLDBPool.Emp’)
    AND sc.column_id IS NULL
    ORDER BY c.column_id

    — Create Statistics on DOB column
    CREATE STATISTICS st_BirthDate
    ON mySQLDBPool.Emp(DOB)
    WITH FULLSCAN

    — When were statistics on indexes last updated
    SELECT ‘Index Name’ = i.name, ‘Statistics Date’ = STATS_DATE(i.object_id, i.index_id)
    FROM sys.objects AS o WITH (NOLOCK)
    JOIN sys.indexes AS i WITH (NOLOCK)
    ON o.name = ‘Emp’
    AND o.object_id = i.object_id
    ORDER BY STATS_DATE(i.object_id, i.index_id);

    — Update statistics on all indexes in the table
    UPDATE STATISTICS mySQLDBPool.Emp
    WITH FULLSCAN


    — Script to shrink database
    DBCC SHRINKDATABASE(N’SQLDBPool’ )
    GO

    — Shrink data file (truncate only)
    DBCC SHRINKFILE (N’SQLDBPool_Data’ , 0, TRUNCATEONLY)
    GO

    — Script to shrink Shrink data file – Very Slow and Enhances the fragmentation
    DBCC SHRINKFILE (N’SQLDBPool_Data’ , 10)
    GO
    — Script Shrink transaction log file
    DBCC SHRINKFILE (N’SQLDBPool_Log’ , 0, TRUNCATEONLY)
    GO

    — Script to create view
    CREATE VIEW emp_view
    AS
    SELECT *
    FROM mySQLDBPool.emp

  • SQL Server Services

    As per the options you choose during the SQL Server installation, it will install below services on server.

    SQL Server Database Services – The service is used for SQL Server relational Database Engine.

    SQL Server Agent – is used for scheduling. It executes jobs, monitors SQL Server, send alerts, and enables automation of some of the administrative tasks.

    Analysis Services – Provides online analytical processing (OLAP) and data mining functionality for business intelligence applications.

    Reporting Services – Manages, executes, creates, schedules, and delivers reports.

    Integration Services –is used for SSIS package. It provides management support for Integration Services package storage and execution.

    SQL Server Browser – The name resolution service that provides SQL Server connection information for client computers. It is used for named instance only.

    Full-text search – Provided full text index and searching facility for BLOB columns.

    SQL Server Active Directory Helper – Publishes and manages SQL Server services in Active Directory.

    SQL Writer – Allows backup and restore applications to operate in the Volume Shadow Copy Service (VSS) framework.

  • Backup Start Date Time and Finish Date Time

    As best practice it is recommended that you have to backup date time with the backup file name so anyone can get the idea of Backup creation.

    Sometimes due some issue we took backup without specifying the datetime with the backup file name so during restore we are unsure that how much data backed up in the backup file, type of backup, Is it Copy only and more.

    SQL Server stores the Backup Metadata into backup header. You can restore header only command to get the required information.

    RESTORE headeronly FROM disk = ‘c:\jshah.bak’ 

    Column Name Values Description
    BackupName NULL  
    BackupDescription NULL  
    BackupType 1 Backup type:
    1 = Database
    2 = Transaction log
    4 = File
    5 = Differential database
    6 = Differential file
    7 = Partial
    8 = Differential partial
    ExpirationDate NULL  
    Compressed 0 0 = Un-Compressed Backup
    1 = Compressed Backup
    Position 1  
    DeviceType 2  
    UserName JShah  
    ServerName SQLDBPool  
    DatabaseName jshah  
    DatabaseVersion 655  
    DatabaseCreationDate 12/31/10 9:55 AM  
    BackupSize 1453056  
    FirstLSN 28000000006000100  
    LastLSN 28000000013000000  
    CheckpointLSN 28000000006000100  
    DatabaseBackupLSN 0  
    BackupStartDate 12/31/10 10:06 AM  
    BackupFinishDate 12/31/10 10:06 AM  
    SortOrder 52  
    CodePage 0  
    UnicodeLocaleId 1033  
    UnicodeComparisonStyle 196609  
    CompatibilityLevel 100  
    SoftwareVendorId 4608  
    SoftwareVersionMajor 10  
    SoftwareVersionMinor 0  
    SoftwareVersionBuild 2757  
    MachineName SQLDBPool  
    Flags 512 1 = Log backup contains bulk-logged operations.
    2 = Snapshot backup.
    4 = Database was read-only when backed up.
    8 = Database was in single-user mode when backed up.
    16 = Backup contains backup checksums.
    32 = Database was damaged when backed up, but the backup operation was requested to continue despite errors.
    64 = Tail log backup.
    128 = Tail log backup with incomplete metadata.
    256 = Tail log backup with NORECOVERY.
    BindingID 85A5505D-ADB1-4B33-A181-549DC520A0F8  
    RecoveryForkID 03DE5437-1E27-4885-9011-91CFED12338A  
    Collation SQL_Latin1_General_CP1_CI_AS  
    FamilyGUID 03DE5437-1E27-4885-9011-91CFED12338A  
    HasBulkLoggedData 0 1 = Yes
    0 = No
    IsSnapshot 0 1 = Yes
    0 = No
    IsReadOnly 0 1 = Yes
    0 = No
    IsSingleUser 0 1 = Yes
    0 = No
    HasBackupChecksums 0 1 = Yes
    0 = No
    IsDamaged 0 1 = Yes
    0 = No
    BeginsLogChain 0 1 = Yes
    0 = No
    HasIncompleteMetaData 0 1 = Yes
    0 = No
    IsForceOffline 0 1 = Yes
    0 = No
    IsCopyOnly 0 1 = Yes
    0 = No
    FirstRecoveryForkID 03DE5437-1E27-4885-9011-91CFED12338A  
    ForkPointLSN NULL  
    RecoveryModel FULL  
    DifferentialBaseLSN NULL  
    DifferentialBaseGUID NULL  
    BackupTypeDescription Database  
    BackupSetGUID 62EB4399-C119-42C2-91F1-BF0FF19CB896  
    CompressedBackupSize 1453056  
  • Stop successfull backup loging messages in SQL Server Error Log?

    Whenever backup peformed on SQL Server, it records the backup entry in the SQL Server. Because of that error log file grows and sometimes we are missing important information from there.

    For example,

    use master
    backup database jshah to disk = 'c:\jshah.bak'

    Above command will log the below message in the SQL Server error log.
    Backup Message:
    Database backed up. Database: jshah, creation date(time): 2010/12/31(09:55:22), pages dumped: 178, first LSN: 28:60:170, last LSN: 28:130:1, number of dump devices: 1, device information: (FILE=1, TYPE=DISK: {‘c:\jshah.bak’}). This is an informational message only. No user action is required.

    Solution
    As a solution we can turn on the trace flag 3226 to stop loging of sucessfull backup message.

    You can turn it on either using SQL Server Service Starup Parameter (-T 3226) or using DBCC TRACEON command.

    -- To turn on the trace flag at global level
    DBCC TRACEON (3226,-1)
    -- To turn off the trace flag at global level
    DBCC TRACEOFF (3226,-1)
  • Transaction Log Backup

    Transaction Log Backup
    In Full or Bulk Logged recovery models, it is very important that we have scheduled periodic Transaction Log backups so it will help us to maintain the the size of the transaction log within reasonable limits and will allow for the recovery of data with the least amount of data loss in case of any failure.

    Transaction Log backups come in three forms:

    Pure Log Backup: —A Pure Log backup contains only transactions and is completed when the database is in Full recovery model or Bulk Logged recovery model, but no bulk operations have been executed. In case of Bulk Logged recovery Bulk Operations are minimally logged.

    Bulk Log Backup: —Bulk Log backups contain both transactional data and any physical extents modified by bulk operations while the database was in Bulk Logged recovery.

    Tail Log Backup: —Tail Log backups are completed when the database is in Full or Bulk Logged recovery prior to a database restoration to capture all transaction log records that have not yet been backed up. It is possible in some instances to execute a Tail Log backup even if the database is damaged.

    Pure or Bulk Log Backup Example
    BACKUP LOG SQLDBPool
    TO DISK = ‘D:\SQLBackups\SQLDBPool.TRN’

    Tail Log Backup Example
    BACKUP LOG SQLDBPool
    TO DISK = ‘D:\SQLBackups\SQLDBPoolTailLog.TRN’
    WITH NO_TRUNCATE