General Queries Used
General Queries Used
1
CITOSS (FTP-PASS) SQL DBA queries
Document Information
Version Author
Date Remarks
Number
5-Feb-2018 Daily SQL DBA Nitesh Koushik Sudharshan
1.0 Queries – Initial
Version
General Queries - which needs to be executed and output, has to be checked on daily basis.
2
CITOSS (FTP-PASS) SQL DBA queries
Blocking - SPIDs (SQL SERVER PROCESS ID) define an atomic operation and are independent, they can
often compete with each other depending on their Transaction Isolation levels, the objects they are
accessing, and the operation they are performing.
We can identify the lock/block of table for a particular DB by the below commands
The below query is the modification of sp_who with the additional information.
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock ( spid int, dbid int, objId int, indId int,
Type char(4), resource nchar(32), Mode char(8), status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who ( spid int, ecid int, status char(30),
loginame char(128), hostname char(128),
blk char(5), dbname char(128), cmd char(16)
--
, request_id INT --Needed for SQL 2008 onwards
--
)
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select left(loginame, 28) as loginame,
left(db_name(dbid),128) as DB,
left(object_name(objID),30) as object,
max(mode) as [ToLevel],
Count(*) as [How Many],
Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for
command],
l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame
Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame,
DB, object
3
CITOSS (FTP-PASS) SQL DBA queries
Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
WHERE EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid )
Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select left(loginame, 30) as loginame, l.spid,
left(db_name(dbid),15) as DB,
left(object_name(objID),40) as object,
mode ,
blk,
l.status
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status
The below query is how to find the blocking process of all the DB objects – This will
provide you the lead blocker of the chain.
SELECT
spid
,sp.status
,loginame = SUBSTRING(loginame, 1, 12)
,hostname = SUBSTRING(hostname, 1, 12)
,blk = CONVERT(char(3), blocked)
,open_tran
,dbname = SUBSTRING(DB_NAME(sp.dbid),1,10)
,cmd
,waittype
,waittime
,last_batch
,SQLStatement =SUBSTRING
(
qt.text,
er.statement_start_offset/2,
(CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
ELSE er.statement_end_offset
4
CITOSS (FTP-PASS) SQL DBA queries
END - er.statement_start_offset)/2
)
FROM master.dbo.sysprocesses sp
LEFT JOIN sys.dm_exec_requests er
ON er.session_id = sp.spid
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE spid IN (SELECT blocked FROM master.dbo.sysprocesses)
AND blocked = 0
The below query is the modification of sp_who2 with the additional information.
This will give you more troubleshooting information of SP_WHO2. It also contains the SQL Statement
being run, so instead of having to execute a separate DBCC INPUTBUFFER, the statement being executed
is shown in the results. It also shows the reads and writes for the current command, along with the
number of reads and writes for the entire SPID. It also shows the protocol being used (TCP, NamedPipes,
or Shared Memory). The lead blocker below will show in the BlkBy column as -1
USE [master]
5
CITOSS (FTP-PASS) SQL DBA queries
ClientAddress = con.client_net_address ,
Authentication = con.auth_scheme ,DatetimeSnapshot = GETDATE(),
plan_handle = er.plan_handle
FROM sys.dm_exec_requests er LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
OUTER APPLY ( SELECT execution_count = MAX(cp.usecounts)
FROM sys.dm_exec_cached_plans cp WHERE cp.plan_handle = er.plan_handle ) ec
OUTER APPLY ( SELECT lead_blocker = 1 FROM master.dbo.sysprocesses sp
WHERE sp.spid IN
(SELECT blocked FROM master.dbo.sysprocesses WITH (NOLOCK) WHERE blocked != 0)
AND sp.blocked = 0 AND sp.spid = er.session_id ) lb
WHERE er.sql_handle IS NOT NULL AND er.session_id != @@SPID
ORDER BY CASE WHEN lb.lead_blocker = 1 THEN -1 * 1000 ELSE -
er.blocking_session_id END,
er.blocking_session_id DESC,
er.logical_reads + er.reads DESC,
er.session_id;
Below query will be providing more CPU usage detailed query details.
SELECT TOP 100
object_name(objectID)
,[Avg CPU Time] = total_worker_time/execution_count
,execution_count
,Plan_handle
,query_plan
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle)
ORDER BY total_worker_time/execution_count DESC;
Below query to view active connection – based on users and based on applications
6
CITOSS (FTP-PASS) SQL DBA queries
Based on Users
SELECT
CPU = SUM(cpu_time)
,WaitTime = SUM(total_scheduled_time)
,ElapsedTime = SUM(total_elapsed_time)
,Reads = SUM(num_reads)
,Writes = SUM(num_writes)
,Connections = COUNT(1)
,[login] = original_login_name
from sys.dm_exec_connections con
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = con.session_id
GROUP BY original_login_name
Based on Applications
SELECT
CPU = SUM(cpu_time)
,WaitTime = SUM(total_scheduled_time)
,ElapsedTime = SUM(total_elapsed_time)
,Reads = SUM(num_reads)
,Writes = SUM(num_writes)
,Connections = COUNT(1)
,Program = program_name
FROM sys.dm_exec_connections con
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = con.session_id
GROUP BY program_name
ORDER BY cpu DESC
To View all the SPIDs (SQL SERVER PROCESS ID) of the current SQL DB server
SELECT * FROM sys.dm_exec_sessions
To Find the SPID status, because SPID is defined as a connection, it is not always
running (or executing)
SELECT SPID = er.session_id ,
Status = ses.status ,
[Login] = ses.login_name ,
Host = ses.host_name ,
BlkBy = er.blocking_session_id ,
DBName = DB_Name(er.database_id) ,
CommandType = er.command ,
SQLStatement = st.text ,
ObjectName = OBJECT_NAME(st.objectid) ,
ElapsedMS = er.total_elapsed_time ,
CPUTime = er.cpu_time ,
IOReads = er.logical_reads + er.reads ,
IOWrites = er.writes ,
LastWaitType = er.last_wait_type ,
StartTime = er.start_time ,
Protocol = con.net_transport ,
ConnectionWrites = con.num_writes ,
ConnectionReads = con.num_reads ,
ClientAddress = con.client_net_address ,
Authentication = con.auth_scheme
7
CITOSS (FTP-PASS) SQL DBA queries
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
To identify all the DB space. (Needs to execute 15 days once in Non Prod and Production
environment)
insert into
#dbsize(Dbname,dbstatus,Recovery_Model,file_Size_MB,Space_Used_MB,Free_Space_MB)
exec sp_msforeachdb
'use [?];
select DB_NAME() AS DbName,
CONVERT(varchar(20),DatabasePropertyEx(''?'',''Status'')) ,
CONVERT(varchar(20),DatabasePropertyEx(''?'',''Recovery'')),
sum(size)/128.0 AS File_Size_MB,
sum(CAST(FILEPROPERTY(name, ''SpaceUsed'') AS INT))/128.0 as Space_Used_MB,
SUM( size)/128.0 - sum(CAST(FILEPROPERTY(name,''SpaceUsed'') AS INT))/128.0 AS
Free_Space_MB
from sys.database_files where type=0 group by type'
8
CITOSS (FTP-PASS) SQL DBA queries
9
CITOSS (FTP-PASS) SQL DBA queries
select d.Dbname,d.dbstatus,d.Recovery_Model,
(file_size_mb + log_file_size_mb) as DBsize,
d.file_Size_MB,d.Space_Used_MB,d.Free_Space_MB,
l.Log_File_Size_MB,log_Space_Used_MB,l.log_Free_Space_MB,fs.Freespace as
DB_Freespace
from #dbsize d join #logsize l
on d.Dbname=l.Dbname join #dbfreesize fs
on d.Dbname=fs.name
order by Dbname
create table #ls (name varchar(255), LogSize real, LogSpaceUsed real, Status int)
10
CITOSS (FTP-PASS) SQL DBA queries
from msdb..backupset
where database_name = b.database_name
and type = 'D')
left join ::fn_virtualfilestats(-1, -1) as vfs
on d.database_id = vfs.DbId
join #ls as ls
on d.name = ls.name
group by d.name, DATABASEPROPERTYEX(d.name, 'Status'),
case when DATABASEPROPERTYEX(d.name, 'IsAutoCreateStatistics') = 1
then 'ON' else 'OFF' end,
case when DATABASEPROPERTYEX(d.name, 'IsAutoUpdateStatistics') = 1
then 'ON' else 'OFF' end,
case when DATABASEPROPERTYEX(d.name, 'IsAutoShrink') = 1
then 'ON' else 'OFF' end,
case when DATABASEPROPERTYEX(d.name, 'IsAutoClose') = 1
then 'ON' else 'OFF' end,
DATABASEPROPERTYEX(d.name, 'Collation'),
DATABASEPROPERTYEX(d.name, 'Updateability'),
DATABASEPROPERTYEX(d.name, 'UserAccess'),
page_verify_option_desc,
d.compatibility_level,
DATABASEPROPERTYEX(d.name, 'Recovery'),
ls.LogSize, ls.LogSpaceUsed, b.backup_start_date;
11
CITOSS (FTP-PASS) SQL DBA queries
12