Find SQL Server deatils


, , ,

Sometimes DBA’s need to quickly extract few SQL Server details like
SQL Server Name
Instance Name
IP Address
TCP Port
Product Name
SP Level
Product Version

Many a times we extract this information by running multiple queries or toggling multiple windows, this T-SQL script will help you to extract same information through a single execution.
You can download T-SQL script from Microsoft gallery.

Basically in this script I have demonstrated how to use SERVERPROPERTY and CONNECTIONPROPERTY functions available in SQL Server 2008 and higher.

Hope this helps…!


SQL Server – Finding Last Backup & Restore Date for All Database


, ,

Many a times we need to find when my database last backed up or when it was last restored.
Below is the quick script i use to find last backup and restore dates.

Script to find last backup date
db.Name AS DatabaseName,
CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101) AS LastBackUpDate
sys.sysdatabases db
LEFT JOIN msdb.dbo.backupset bus ON bus.database_name =

Script to find last restored date
db.Name AS DatabaseName,
CONVERT(VARCHAR(12), MAX(rh.restore_date), 101) AS LastBackUpDate
sys.sysdatabases db
LEFT JOIN msdb.dbo.restorehistory rh ON rh.destination_database_name =
GROUP BY db.Name

Hope this helps…!

SQL Server: Instant File Initialization Exceptions


, , ,

Happy to inform all my blog readers this particular post has won me SILVER in TechNet Guru Award under SQL Server General and Database Engine Technical Guru – February 2014.
Visit TechNet Guru Awards – February 2014 for winner list


DBA’s are always on the lookout for Performance Quick Wins to improve the SQL Server performance under their care, one of the highly recommended performance booster is to have Instant File Initialization (IFI) enabled. IFI is a feature that’s seemingly simple;it allows file allocation requests to skip zero initialization on creation as a result, file allocation requests can occur instantly.

I will not get into the details of IFI, we already have good amount of articles on this topic and I personally recommend Instant Initialization – What, Why and How? by Kimberly Tripp and How and Why to Enable Instant File Initialization by Cindy Gross and Denzil Ribeiro.
Basic intention of this article is to demonstrate the Instant File initialization exceptions, which means SQL Server engine will go ahead with zeroing out disk space inspite of having IFI enabled.

Performing the test

Let me check if SQL Server is able to use IFI in my environment by creating a database. If it is enabled you will see message in SQL Server error log for the zeroing out of the log files, and if it is not enabled, you will see messages for the zeroing out for both log files and data files.

I am creating a dummy database with 10 GB data file and 1 GB log file total size would be 11 GB.

To see which files are being zeroed out, this article uses the undocumented trace flag 3004. Undocumented means it is safe to use in production but any support related to this command cannot be claimed from Microsoft.It also means that any change can be made to this command without officially notifying end user so unexpected results might come if used on same environment after some time. Although their usage is safe, keep in mind to use it in test environments only to avoid any impact to production processes.
Trace flag 3004 shows information about backups and file creations, Trace flag 3605 redirects the output to the SQL error log.
USE master;
--Set Trace Flags 3004 and 3605 to On.
DBCC TRACEON(3004,-1);
DBCC TRACEON(3605,-1);
--Create a dummy database to see what output is sent to the SQL Server Error Log
(NAME = N'IFITest', FILENAME = N'C:\IFITest.mdf',SIZE = 10GB)
(NAME = N'IFITest_log', FILENAME = N'c:\IFITest_log.ldf',SIZE = 1GB)

It took 4 sec to create above database on my laptop, let me check SQL errorlog.

2014-02-26 19:12:36.090 spid56       Zeroing c:\IFITest_log.ldf from page 0 to 131072 (0x0 to 0x40000000)
2014-02-26 19:12:40.190 spid56       Zeroing completed on c:\IFITest_log.ldf
2014-02-26 19:12:40.300 spid56       Starting up database 'IFITest'.
2014-02-26 19:12:40.320 spid56       FixupLogTail(progress) zeroing c:\IFITest_log.ldf from 0x5000 to 0x6000.
2014-02-26 19:12:40.320 spid56       Zeroing c:\IFITest_log.ldf from page 3 to 483 (0x6000 to 0x3c6000)
2014-02-26 19:12:40.330 spid56       Zeroing completed on c:\IFITest_log.ldf

As you can see in above errorlog result, only log file is zeroing out it confirms IFI is enabled in my environment.

Just to cross verify, I create above database by interchanging data file size and log file size but total size of the database remains the same i.e. 11 GB.

Use Master
(NAME = N'IFITest', FILENAME = N'C:\IFITest.mdf',SIZE = 1GB)
(NAME = N'IFITest_log', FILENAME = N'c:\IFITest_log.ldf',SIZE = 10GB)

As expected it took me 1 min 35 sec to create database, this also confirms IFI is in action in my environment.

If you want to check if Instant File Initialization is enabled in your environment then I would recommend you to read

Instant File Initialization Exception Scenarios

Now I demonstrate you few different scenarios wherein IFI has to zero out data files in spite of having IFI enabled.

Scenario 1: Enable Trace Flag 1806.

Turning on trace flag 1806 will disable instant file initialization.

DBCC TRACEON(1806 , -1)
(NAME = N'IFITest', FILENAME = N'C:\IFITest.mdf',SIZE = 10GB)
(NAME = N'IFITest_log', FILENAME = N'c:\IFITest_log.ldf',SIZE = 1GB)
DBCC TRACEOFF(1806 , -1)

Let me check errorlog.

2014-02-26 19:05:41.440 spid56       DBCC TRACEON 1806, server process ID (SPID) 56. This is an informational message only; no user action is required.
2014-02-26 19:05:49.240 spid56       Zeroing C:\IFITest.mdf from page 0 to 1310720 (0x0 to 0x280000000)
2014-02-26 19:06:32.070 spid56       Zeroing completed on C:\IFITest.mdf
2014-02-26 19:06:32.160 spid56       Zeroing c:\IFITest_log.ldf from page 0 to 131072 (0x0 to 0x40000000)
2014-02-26 19:06:37.190 spid56       Zeroing completed on c:\IFITest_log.ldf
2014-02-26 19:06:37.320 spid56       Starting up database 'IFITest'.
2014-02-26 19:06:37.330 spid56       FixupLogTail(progress) zeroing c:\IFITest_log.ldf from 0x5000 to 0x6000.
2014-02-26 19:06:37.330 spid56       Zeroing c:\IFITest_log.ldf from page 3 to 483 (0x6000 to 0x3c6000)
2014-02-26 19:06:37.340 spid56       Zeroing completed on c:\IFITest_log.ldf

As you can see in above result set, enabling trace flag 1806 forces SQL Server engine to zero out both data and log files and it took 48 sec to create database.

Scenario 2: Transparent Data Encryption (TDE).

When you have enable Transparent Data Encryption on your database then SQL Server Engine will ignore your IFI settings and go ahead with zero initialization of data files.

USE master;
CREATE CERTIFICATE MyServerCert WITH SUBJECT = 'Test Certificate';

In my above query I encrypted the database and then I altered data file from 10GB to 15GB, let us see errorlog result.

2014-02-26 19:16:28.770 spid56       Setting database option ENCRYPTION to ON for database IFITest.
2014-02-26 19:16:28.770 spid18s      Beginning database encryption scan for database 'IFITest'.
2014-02-26 19:16:42.140 spid56       Zeroing C:\IFITest.mdf from page 1310720 to 1966080 (0x280000000 to 0x3c0000000)
2014-02-26 19:17:06.050 spid56       Zeroing completed on C:\IFITest.mdf

As you can see in result set, SQL Server Engine is zeroed out data file and it took 24 sec to extend data file and without encryption same query took only 1 sec.

Refer technet article Transparent Data Encryption (TDE) to know more about Transparent Data Encryption.

Scenario 3: CHECKDB.

One more case wherein SQL Server Engine has to zero initialize data files is when we run DBCC CHECKDB.

Use IFITest

Below errorlog result clearly shows SQL Server Engine is zeroing out data files.

2014-02-26 19:25:08.360 spid53       Zeroing C:\IFITest.mdf:MSSQL_DBCC9 from page 0 to 1310720 (0x0 to 0x280000000)
2014-02-26 19:25:08.360 spid53       Zeroing completed on C:\IFITest.mdf:MSSQL_DBCC9
2014-02-26 19:25:08.650 spid53       DBCC CHECKDB (IFITest) executed by \********* found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 0 seconds.  Internal database snapshot has split point LSN = 00000013:00000040:0001 and first LSN = 00000013:0000003f:0001.
Refer technet article DBCC CHECKDB to know more about DBCC CHECKDB.

Scenario 4: Database Snapshot.

When we create database snapshot, SQL Server Engine go ahead and zero initializes data file.

CREATE Database IFITest_SS
ON (Name'IFITest' , Filename ='C:\')

And errorlog result indicates zero initialization of data files.

2014-02-26 19:27:46.890 spid53       Zeroing C:\ from page 0 to 1310720 (0x0 to 0x280000000)
2014-02-26 19:27:46.890 spid53       Zeroing completed on C:\
2014-02-26 19:27:46.940 spid53       Starting up database 'IFITest_SS'.
Refer technet article Create a Database Snapshot to know more about Database Snapshot.


Basically, with Instant File Initialization turned on it cuts out database creation or data file growth time, most DBA’s are aware of this fact, but most of us not aware of the fact that in some exceptional cases Instant File Initialization has to zero initializes data files, I have demonstrated four such scenarios in this article.


Magical Object Explorer Details pane


In this blog I just show you how effectively we can make use of SSMS object Explorer Detail pane.

Once you are in SSMS, go to View-> Object Explorer Details alternatively you can use shortcut key F7 to access Object Explorer window as shown below.
Object Explorer Detail
This brings you the Object Explorer Detail window in the same location where we normally have the Query window.

Object Explorer Detail Pane

Now you can navigate to any node in object explorer or click any node in object explorer and it will give you the related detail on Object Explorer Detail pane as shown in the above screen. Here I have selected SQL Server Agent node on Object Explorer and in Object Explorer Detail pane we can see all the objects related to SQL Server Agent.
Now I will show you how can we make best you of Object Explorer Detail pane to script out all the Jobs in a single click.
Navigate to SQL Server Agent -> Jobs, Object Explorer Detail pane will display all the jobs, now select any job and say Ctrl+A all jobs will be selected, now right click then say Script Job As -> New Query Editor Window as shown below.

export sql agent jobs

Now you have script out all your jobs in a single query window, no need to go to each job to generate script. Same technique can be used to generate script of various other objects like tables, views, procedures etc.

Will explore some more features of Object Explorer Detail pane in coming days.

Hope this helps.!!!

SQL Server: Misleading Database Initial Size Label


, ,

Happy to inform all my blog readers this particular post has won me GOLD in TechNet Guru Award under SQL Server General and Database Engine Technical Guru – January 2014.
Visit TechNet Guru Awards – January 2014 for winner list


In SQL Server every database has a property Initial Size (MB) which can be seen in database properties. It’s the size that is specified during creation of the database. You can either explicitly specify this in the CREATE DATABASE statement,
or you can have SQL Server implicitly copy it from the model database.Please refer


Well, we all know this, but the question is where exactly this information is stored, can I change Initial size property post its creation, can we shrink a database below its initial size.

In my view, the “Initial size” label that you see when you look at the file properties in SSMS is itself misleading, let us examine it.

Performing the test

Create the database as below.

USE master
( NAME = MyDB_dat,
FILENAME = 'c:\MyDB.mdf',
SIZE = 10MB,
( NAME = MyDB_log,
FILENAME = 'c:\MyDB.ldf',


Now check the initial size of mydb (Right click on mydb ->Properties – > files)

Data file has initial size of 10 mb and log file 3 mb as specified in our CREATE DATABASE statement, now alter the database file as below.

NAME = N'MyDB_dat',
SIZE = 100MB )

Again check the initial size of mydb(Right click on mydb ->Properties – > files)

Data file initial file size is changed to 100 MB which is current size not initial size, from the above result, it is clear that there is no such thing as “initial size” there is only one property visible and that is the actual size(current

Even the “Initial size” property in SSMS just shows actual size, not the initial size.

Now let me shrink the database and examine to what size it will shrink.


From above result we can clearly make out database has shrinked to the size specified during its creation which is 10 MB.

How does database know its initial size?

Well how come that DBCC SHRINKDATABASE knows the initial size then? Even after you have changed the size.

The first page of a database file is the file header page,and it stores information of various properties.

By default, the output of DBCC PAGE is sent to the errorlog. If you want the output to come back to your current connection, need to turn on trace flag 3604, DBCC TRACEON(3604),
refer how to use DBCC Page.

DBCC Page would return various properties, we need to concentrate on Size, MaxSize & MinSize, at the creation of database all three properties are set as per the sizes you specified, in our case Size is 10 mb, MaxSize is 100 Mb and MinSize is also 10 MB
which we had specified during database creation.

In the above result all three sizes are in terms of data pages, Size & MinSize is 1280 pages corresponds to 10 MB and MaxSize is 12800 which is 100 MB.

1280 = (1280*8)/1024 = 10 MB
1280 – total no of pages. 8 – 1 page is 8 KB
1024 – 1MB is 1024 KB

Let me alter the file size and see what will happen to these three values.

NAME = N'MyDB_dat',
SIZE = 100MB )as you can see that size property has changed to reflect the new size which is 12800 data pages (100 mb). However MinSize still holds the initial size and it is the minimum size to which DBCC SHRINKDATABASE can go to.

Can I shrink database below Initial size?

The question is can i change this MinSize. DBCC SHRINKDATABASE Command will shrink database to a size which is specified during database creation which is MinSize, but DBCC SHRINKFILE reduces the size of a file to smaller than its originally created size. The
minimum file size for the file is then reset to the newly specified size. Refer
DBCC shrinkfile

Let us check that.

, 2)
i try and shrink data file to 2 mb and DBCC PAGE MinSize should reflect this new MinSize.

MinSize has new value now, and henceforth this value will be the reference point for Database shrink, let me modify data file to 100 mb and then shrink database and will see to what size database will shrink.

= N
= 100MB )

DBCC SHRINKDATABASE has shrinked data files to 2 mb, that means we have successfully changed MinSize property to new value.

If you are shrinking files outside of an emergency event, you need to change the way you’re doing things. Refer below articles.


Basically, database initial size is just a concept, from a DBA perspective there is no such thing as “initial size” there is only one property visible for a DBA and that is the current size or actual size.

Minimum size is stored in Page header and DBCC SHRINKDATABASE refers to that minsize property when its shrink database if actual data size is less than MinSize.

DBCC SHRINKFILE can shrink files to less than its initial size.


Rebuild or Reorganize: Smart SQL Server Index Maintenance


, , , , , ,

To keep the indexes in proper shape, a timely defragmentation is necessary. There is no any thumb rule when to defragment the indexes, it depends on the environment. However, this script could be scheduled as per ones need to make sure that the indexes gets defragmented when need.

Firstly do not blindly REBUILD every index which not only increases your I/O’s but also create huge amount of T-log, and if you have enabled mirroring or log shipping then it would take considerable time to ship these logs, defragment your indexes smartly.

In our environment we follow the index maintenance as given below:

If fragmentation is less than 10% or index page count is less than 100 no action will be taken.

If fragmentation is between 10-30% then the index will be reorganized and statistics will be updated. (REORGANISE index will not update STATISITCS automatically)

If fragmentation is greater than 30% index will be rebuilt.

You can also download this script from Microsoft Gallery

Hope this helps.!

Merry Christmas and Best Wishes for the New Year!!

sqlerrorsA big thank you for everyone who supported me and the many visitors
who have come along to read and comment on my Blog in 2013.
I hope you all return here again in 2014.
May you have a wonderful Christmas with your loved ones and enjoy all the blessing the season brings.
Merry Christmas and Best Wishes for the New Year!!

Log shipping false errors messages – 14420


, , , , , ,

We recently migrated our SQL Server 2008 R2 and SAN storage to the new infrastructure, I have log shipping setup on few databases and to retain all the jobs I restored MSDB database on the new server, post migration I synced primary and secondary servers, enabled all log shipping related jobs and the entire process was successful, but few hours later Primary Server started generating alerts, error 14420 “The log shipping primary database [ServerName].[DatabaseName] has backup threshold of 60 minutes and has not performed a backup log operation for 120 minutes.

I started my investigation with sp_readeerorlog, I found a lot of error messages as below.

To confirm my log shipping status I checked Log backup , log copy and log restore jobs and all were running successfully, my last log backup was 15 min back and it was successfully restored on secondary server as shown below.

On Primary Server.

Secondary Server.

Now I am pretty sure there is no problem with log shipping, but why server generating alerts, on further investigation using following query on Primary server.

Select * from msdb.dbo.log_shipping_monitor_primary

last_backup_date column was not at all updating with latest dates and it was showing date and time of last backup just before we migrated to new server.
This helped me a lot for my further investigation, and somewhere I read a suggestion just to check my server name.

Select ServerProperty('ServerName'), @@ServerName

Above query returned two different names,ServerProperty(‘ServerName’) returned actual server, whereas @@ServerName returned the name we had assigned to the server during SQL Installation(SQL Server Setup sets the server name to the computer name during installation )

When you run following queries all should return you same server name.

Select ServerProperty('ServerName')
Select @@ServerName
Select primary_server from msdb.dbo.log_shipping_monitor_primary

This happens if you install SQL Server and later you change Server name, to solve my problem I have to drop old server name and add it again with new server name as shown in the following queries

EXEC sp_dropserver 'OLD_SERVER_NAME'
EXEC sp_addserver 'NEW_SERVER_NAME', 'local'

You need to restart your SQL Service for changes to take effect, no more error messages now.

find Enterprise-only features in your database


, , , , ,

I have SQL Server that was installed as enterprise edition, we have never utilized the enterprise-only features on this particular server and want to downgrade to Standard edition so that we can make use of this enterprise license in some other server.
There’s an easy way to tell whether the database contains enterprise-only features. In SQL Server 2008 onwards a new DMV sys.dm_db_persisted_sku_features has been added that will report you which enterprise only features are present in a database. Let’s check it out.

Method 1:
You need to run below query on every database to check for enterprise-only features.

SELECT * FROM sys.dm_db_persisted_sku_features

Method 2:
The following query will report all enterprise-only features from all databases.

Declare @EntFeatures Table(DbName NVARCHAR(255),[Enterprise feature] NVARCHAR(255))
INSERT INTO @EntFeatures
exec sp_msforeachdb 'select "?" AS DatabaseNames,feature_name from [?].sys.dm_db_persisted_sku_features'
SELECT * FROM @EntFeatures

Method 3:
The following query makes use of cursor to achieve the same result as in method 2.

Declare @dbid Int
Declare @STR Varchar(100)
Declare @EntFeatures Table(DbName NVARCHAR(255),[Enterprise feature] NVARCHAR(255))
Declare rs scroll cursor for
Select database_id From sys.databases
open rs
fetch first from rs into @dbid
while @@fetch_status= 0
Select @STR = 'use ' + db_name (@dbid) +
CHAR(13) + ' SELECT db_name(),feature_name FROM sys.dm_db_persisted_sku_features'
Insert Into @EntFeatures
fetch next from rs into @dbid 
Close rs 
Deallocate rs 
Select * from @EntFeatures

sys.dm_db_persisted_sku_features DMV only reports below four features.

  • Data compression
  • Partitioning
  • Transparent data encryption
  • Change data capture

As per MSDN Library even Database Snapshot & Online Indexing are enterprise-only features , if you have enabled these features in your database it will not be reported by this DMV.
To make sure I created a database snapshot and ran this DMV but it did not report database snapshot as enterprise-only feature same is with online indexing which I enabled for one of my maintenance plans but DMV again missed out this as well.

Find Windows and SQL Server Last Restart time


, , , ,

As a routine DBA activity I was analyzing sp_readerrorlog this morning and surprised to see that SQL Server has restarted early this morning.

Here are few different ways that you can make use of to tell when SQL Server was last restarted.

Method 1

sp_readerrorlog 0,1,'Copyright (c)'

Method 2:

SELECT sqlserver_start_time FROM sys.dm_os_sys_info

2013-11-26 01:16:10.757

(1 row(s) affected)

Method 3:

SELECT login_time FROM sys.dm_exec_sessions WHERE session_id = 1

2013-11-26 01:16:24.127

(1 row(s) affected)

Method 4

SELECT create_date FROM sys.databases WHERE name = 'tempdb'

2013-11-26 01:16:13.023

(1 row(s) affected)

Method 5:

Right click on the server name in SSMS and select Reports > Standard Reports > Server Dashboard and you will get a report similar to below report.


Method 6: 

start -> run -> eventvwr

Chose Windows log -> Application
Open filter and enter Event Sources (MSSQLSERVER) and Event Id (17163)

Here is the output of above filter.


Here are a few different ways that you can tell when Windows last rebooted.

Method 1:

Start Task Manager->Performance
Screen below gives you total up time since last restart.

Method 2:

start -> run -> eventvwr
Choose: Windows Log – > System
Open filter and following Event Id’s
6005 to see when the Event Log service was started. It gives the message “The Event log service was started“.
6006 to see when there was a clean shutdown. It gives the message “The Event log service was stopped“.
6008 to see when there was a dirty shutdown. It gives the message “The previous system shutdown at time on date was unexpected“.
6009 is logged during every boot.


Here is the output of above filter.

Hope this helps!