Category Archives: SQL Scripts

How to restart an Interrupted Database Restore in SQL Server?

Steps to restart an Interrupted Database Restore in SQL Server

There may scenario when you are restoring VLDB database backup and the restore database command interrupted due network failure, power failure, SQL Server Service restart or cluster failover. In this kind of scenario you can easily start the interrupted restore from the point of failure using WITH RESTART command.

Before you start restoring the database using WITH RESTART option check database is in Restoring State not in any other state.

You can check the database state either from SSMS object explorer or by executing below T-SQL command

select name,state_desc from sys.databases

Once confirmed that database is in restoring state execute the backup command WITH RESTART clause

RESTORE DATABASE [AdventureWorks]
FROM DISK ='D:\Backup\AdventureWorks.bak'
WITH RESTART, STATS = 20
GO
Advertisements

OpenDataSouce function – to query OLEDB Data Source

OPENDATASOURCE
OpenDataSouce function helps you to get ad hoc connection information as part of a four-part object name as an one time alternative of linked server. You don’t have to specify or create the linked server to query other data sources (i.e. MS Excel, MS Access, MSSQL Older version to newer version etc.) if you are querying it infrequently.

You can use OPENDATASOURCE for the OLEDB data sources those are accessed infrequently, for several time use linked server as it provides more functionality.

You can get more information about the arguments of OpenDataSource function on MSDN site.

To use the OPENDATASOURCE you have to enable the ad hoc distributed queries. You required to have execute permission to use OPENDATASOURCE fucntion.

Execute below query to enable it

EXEC sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE WITH OVERRIDE
GO

Make sure Provider AllowInProcess and DynamiceParameters value is checked. For example lets enable it for SQLNCLI10 provider.

USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'SQLNCLI10', N'AllowInProcess', 1
EXEC master.dbo.sp_MSset_oledb_prop N'SQLNCLI10', N'DynamicParameters', 1
GO

OpenDataSource Examples

-- SQL Server 2000/2005/2008
-- You can use SQLNCLI10 provider for SQL Server 2008 as well
SELECT
    * FROM
OPENDATASOURCE (
   'SQLNCLI', 
   'Data Source=SQLInstanceName;Catalog=DBName;User ID=SQLLogin;Password=Password;').DBName.SchemaName.TableName
   
   
SELECT *
FROM OPENROWSET('SQLNCLI',
   'DRIVER={SQL Server};SERVER=SQLInstanceName;UID=SQLLogin;PWD=Password',
   'select * from DBName..TableName')  
   

-- SQL Server 2012
SELECT
    * FROM
OPENDATASOURCE (
   'SQLNCLI11', 
   'Data Source=SQLInstanceName;Catalog=DBName;User ID=SQLLogin;Password=Password;').DBName.SchemaName.TableName
   
   
SELECT *
FROM OPENROWSET('SQLNCLI11',
   'DRIVER={SQL Server};SERVER=SQLInstanceName;UID=SQLLogin;PWD=Password',
   'select * from DBName..TableName')  

--Access DB
SELECT * FROM OPENDATASOURCE ('Microsoft.ACE.OLEDB.12.0', 
                              'Data Source=D:\MyDB\MyAccessDB.accdb')...TableName   

Common Errors
Error 1#
Msg 7403, Level 16, State 1, Line 1
The OLE DB provider “SQLNCLI11” has not been registered.
Solution: You will get above error if you have mentioned SQLNCLI11 while running OPENDATASOURCE query on SQL Server 2008 or lower version, it will work fine on SQL Server 2011. You can check list of registered provider by browsing Server Objects -> Linked Servers -> Provider in SSMS
Error 2#
Msg 15281, Level 16, State 1, Line 2
SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, see “Surface Area Configuration” in SQL Server Books Online.

Solution: Enable the ad hoc distributed queries by executing above SP_CONFIGURE query.

T-SQL Script to check SQL Server Instance TCP/IP Port Number

SQL Server Error Log

-- Check the error log for port number
EXEC xp_ReadErrorLog 0, 1, N'Server is listening on', N'any', NULL, NULL, 'DESC'
GO

Executing DMV Script

-- you must connect remotely using TCP/IP
SELECT local_tcp_port
FROM   sys.dm_exec_connections
WHERE  session_id = @@SPID
GO

For Dynamic Port Number
— Read the registry for port number

-- Execute below script if SQL Server is configured with dynamic port number
DECLARE       @portNo   NVARCHAR(10)
 
EXEC   xp_instance_regread
@rootkey    = 'HKEY_LOCAL_MACHINE',
@key        =
'Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll',
@value_name = 'TcpDynamicPorts',
@value      = @portNo OUTPUT
 
SELECT [PortNumber] = @portNo
GO

For Static Port Number

-- Execute below script if SQL Server is configured with static port number
DECLARE       @portNo   NVARCHAR(10)
 
EXEC   xp_instance_regread
@rootkey    = 'HKEY_LOCAL_MACHINE',
@key        =
'Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll',
@value_name = 'TcpPort',
@value      = @portNo OUTPUT
 
SELECT [PortNumber] = @portNo
GO

T-SQL Script to Check if LiteSpeed is installed or not on the server

You can execute below script against the SQL Server instance and check whether LiteSpeed is installed on the server or not.

T-SQL script is checking registry to check the LiteSpeed version value.

declare @regkeyval varchar(20), @value varchar(255), @rc int
exec @rc=master.dbo.xp_regread 
  @rootkey= 'hkey_local_machine',
  @key='software\imceda\sqllitespeed\engine',
  @value_name='version',
  @regkeyval=@value output

set @value =isnull(@value,'-') 

if @value <> '-'
select 
 @@servername as SQLInstanceName
,case serverproperty('IsClustered') when 1 then cast(serverproperty('computernamephysicalnetbios') as varchar)
 else cast(serverproperty('machinename') as varchar)
 end as WindowsServerName
,@value as LiteSpeedVersion 
,'LiteSpeed is installed' as LiteSpeedStautsCheck
else
select 
 @@servername as SQLInstanceName
,case serverproperty('IsClustered') when 1 then cast(serverproperty('computernamephysicalnetbios') as varchar)
 else cast(serverproperty('machinename') as varchar)
 end as WindowsServerName
,'LiteSpeed is not installed' as LiteSpeedStautsCheck

T-SQL Script to Check the Native Compressed backup file size and Backup Compression Ratio

First of all make sure backup compression is enabled on the SQL Server. You can execute below query to check the backup compression.

select name,[description],value_in_use from sys.configurations where name like '%backup%'

Execute below script to check the compressed backup file size and backup compression ratio.

Declare @FromDate as datetime
-- Specify the from date value
set @FromDate = GETDATE() -1

SELECT  
   CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS SQLServerName, 
   msdb.dbo.backupset.database_name,  
   CASE msdb..backupset.type  
       WHEN 'D' THEN 'Database'  
       WHEN 'L' THEN 'Log'  
       WHEN 'I' THEN 'Differential'  
   END AS backup_type,  
   msdb.dbo.backupset.backup_start_date,  
   msdb.dbo.backupset.backup_finish_date, 
   msdb.dbo.backupset.expiration_date, 
   DATEDIFF (SECOND, msdb.dbo.backupset.backup_start_date, msdb.dbo.backupset.backup_finish_date) 'Backup Elapsed Time (sec)',
   msdb.dbo.backupset.compressed_backup_size AS 'Compressed Backup Size in KB',
  (msdb.dbo.backupset.compressed_backup_size/1024/1024) AS 'Compress Backup Size in MB',
   CONVERT (NUMERIC (20,3), (CONVERT (FLOAT, msdb.dbo.backupset.backup_size) /CONVERT (FLOAT, msdb.dbo.backupset.compressed_backup_size))) 'Compression Ratio',
   CASE msdb..backupset.type  
       WHEN 'D' THEN 'Database'  
       WHEN 'L' THEN 'Log'  
   END AS backup_type,  
   msdb.dbo.backupset.backup_size,  
   msdb.dbo.backupmediafamily.logical_device_name,  
   msdb.dbo.backupmediafamily.physical_device_name,   
   msdb.dbo.backupset.name AS backupset_name, 
   msdb.dbo.backupset.description 
FROM   msdb.dbo.backupmediafamily  
   INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id 
WHERE 
CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= @FromDate
AND msdb.dbo.backupset.backup_size > 0 
ORDER BY  
   msdb.dbo.backupset.database_name, 
   msdb.dbo.backupset.backup_finish_date

SQL Server – Backup Verification Script – Based on conditions

Problem: There are scenarios where you have to verify the multiple SQL Server instances backup within limited time frame whether it meet your organization backup criteria standards or not.

Solution:
You can execute below T-SQL script to check the backup status as per your organization standard by assigning backup conditions value to backup criteria variable. You can execute below script either by connecting each SQL Server Instance or execute it by registering all the SQL Server Instances in Central Management Server (CMS).

Below T-SQL Script work with all the versions of MSSQL Server and verify FULL, Differential and Transaction Log Backup. It will check the max backup date and evaluate result based on condition as backup is Passed or Not.

Backup Verification Script will return below values. Column names are self-explanatory.
• SQLInstanceName
• DatabaseName
• db_create_ddate
• DB_Recovery_Model
• dbstatus
• windowsservername
• productversion
• productlevel
• edition
• current_datetime
• last_full_backup_date
• last_diff_backup_date
• last_tran_backup_date
• days_since_last_full_backup
• days_since_last_diff_backup
• hours_since_last_tranlog_backup
• Full_Backup_Stauts
• Diff_Backup_Stauts
• Log_Backup_Stauts
• full_backup_location
• diff_backup_location
• tlog_backup_location

You have to specify the backup condition based on your organization standard by assigning values to below variables.

declare @full_backup_criteria_in_days int
declare @diff_backup_criteria_in_days int
declare @log_backup_criteria_in_hours int

-- specify the backup criteria
set @full_backup_criteria_in_days = 7 -- 7 day older Full Backup is Pass 
set @diff_backup_criteria_in_days = 1 -- 1 day older Diff Backup is Pass 
set @log_backup_criteria_in_hours = 2 -- 2 hours older Log Backup is Pass

Complete Backup Verification Script

declare @full_backup_criteria_in_days int
declare @diff_backup_criteria_in_days int
declare @log_backup_criteria_in_hours int

-- specify the backup criteria
set @full_backup_criteria_in_days = 7 -- 7 day older Full Backup is Pass 
set @diff_backup_criteria_in_days = 1 -- 1 day older Diff Backup is Pass 
set @log_backup_criteria_in_hours = 2 -- 2 hours older Log Backup is Pass

select     
           serverproperty('servername') as SQLInstanceName,
           quotename(bkup_full.[database_name]) as DatabaseName,
            ( select    sdb.crdate
              from      [master]..[sysdatabases] sdb
              where     sdb.name = bkup_full.[database_name]
            ) as [db_create_ddate],           
           databasepropertyex(bkup_full.[database_name],'recovery')  as DB_Recovery_Model,
           databasepropertyex(bkup_full.[database_name],'status')  as dbstatus,       
           case serverproperty('isclustered') 
                        when 1 then cast(serverproperty('computernamephysicalnetbios') as varchar)
                        when 0 then cast(serverproperty('machinename') as varchar)
           end as windowsservername,
           serverproperty('productversion') as productversion,
           serverproperty('productlevel') as productlevel,
           serverproperty('edition') as edition,

           current_timestamp as current_datetime,
		   
		   bkup_full.[backup_finish_date] as [last_full_backup_date],           
		   bkup_diff.[backup_finish_date] as [last_diff_backup_date] ,
		   bkup_log.[backup_finish_date] as [last_tran_backup_date] ,

           datediff(dd, bkup_full.[backup_finish_date], current_timestamp) as [days_since_last_full_backup] ,
           datediff(dd, bkup_diff.[backup_finish_date], current_timestamp) as [days_since_last_diff_backup] ,
           datediff(hh, bkup_log.[backup_finish_date], current_timestamp) as [hours_since_last_tranlog_backup] ,
            
           case 
                        when datediff(dd, bkup_full.[backup_finish_date], current_timestamp) <= @full_backup_criteria_in_days  
                        then 'Pass'
                        else 'Fail'
                        end as Full_Backup_Stauts,
            
            case 
                        when datediff(dd, bkup_diff.[backup_finish_date], current_timestamp) <= @diff_backup_criteria_in_days  then 'Pass'
                        else case when quotename(bkup_full.[database_name]) IN ('[master]') then 'N/A' else 'Fail' end                        
                        end as Diff_Backup_Stauts,

            case 
                        when datediff(hh, bkup_log.[backup_finish_date], current_timestamp) <= @log_backup_criteria_in_hours  then 'Pass'
                        else case when databasepropertyex(bkup_full.[database_name],'recovery') = 'SIMPLE' then 'N/A' else 'Fail' end                        
            end as Log_Backup_Stauts,            

            ( select top 1 [physical_device_name]
              from      [msdb]..[backupmediafamily] bkup_media_family
              where     bkup_media_family.[media_set_id] = bkup_full.[media_set_id]
            ) as [full_backup_location] ,
            ( select top 1  [physical_device_name]
              from      [msdb]..[backupmediafamily] bkup_media_family
              where     bkup_media_family.[media_set_id] = bkup_diff.[media_set_id]
            ) as [diff_backup_location] ,
            ( select top 1  [physical_device_name]
              from      [msdb]..[backupmediafamily] bkup_media_family
              where     bkup_media_family.[media_set_id] = bkup_log.[media_set_id]
            ) as [tlog_backup_location]
         
                             
    from    [msdb]..[backupset] as bkup_full
            left join [msdb]..[backupset] as bkup_log on bkup_log.[database_name] = bkup_full.[database_name]
                                                       and bkup_log.[server_name] = bkup_full.[server_name]
                                                       and bkup_log.[type] = N'L'
                                                       and bkup_log.[backup_finish_date] = ( (select  max([backup_finish_date])
                                                                                            from    [msdb]..[backupset] b2
                                                                                            where   b2.[database_name] = bkup_full.[database_name]
                                                                                                    and b2.[server_name] = bkup_full.[server_name]
                                                                                                    and b2.[type] = N'L') )
            left join [msdb]..[backupset] as bkup_diff on bkup_diff.[database_name] = bkup_full.[database_name]
                                                       and bkup_diff.[server_name] = bkup_full.[server_name]
                                                       and bkup_diff.[type] = N'I'
                                                       and bkup_diff.[backup_finish_date] = ( (select max([backup_finish_date])
                                                                                            from    [msdb]..[backupset] b2
                                                                                            where   b2.[database_name] = bkup_full.[database_name]
                                                                                                    and b2.[server_name] = bkup_full.[server_name]
                                                                                                     and b2.[type] = N'I') )
    where   bkup_full.[type] = N'D'
            and bkup_full.[backup_finish_date] = ( (select  max([backup_finish_date])
                                                 from   [msdb]..[backupset] b2
                                                 where  b2.[database_name] = bkup_full.[database_name]
                                                        and b2.[server_name] = bkup_full.[server_name]
                                                        and b2.[type] = N'D') )
            and exists ( select [name]
                         from   [master]..[sysdatabases]
                         where  [name] = bkup_full.[database_name] )
            and bkup_full.[database_name] <> N'tempdb'