0% found this document useful (0 votes)
22 views12 pages

General Queries Used

Uploaded by

magesh s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views12 pages

General Queries Used

Uploaded by

magesh s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

CITOSS (FTP-PASS) SQL DBA queries

SQL DBA Queries


[CITOSS (FTP-PASS Application)]

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

sp_who, sp_who2, sp_lock

Below query will provide most blocked queries


SELECT OBJECT_NAME(objectid),
BlockTime = total_elapsed_time - total_worker_time,
execution_count,
total_logical_reads
FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle)
ORDER BY total_elapsed_time - total_worker_time DESC

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]

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SELECT SPID = er.session_id,


BlkBy = CASE
WHEN lead_blocker = 1 THEN -1
ELSE er.blocking_session_id END,
ElapsedMS = er.total_elapsed_time,
CPU = er.cpu_time,
IOReads = er.logical_reads + er.reads,
IOWrites = er.writes,
Executions = ec.execution_count,
CommandType = er.command,
LastWaitType = er.last_wait_type,
ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' +
OBJECT_NAME(qt.objectid, qt.dbid),
SQLStatement = SUBSTRING ( qt.text, er.statement_start_offset/2,
CASE WHEN ( CASE WHEN er.statement_end_offset = -1 THEN
LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
ELSE er.statement_end_offset END - er.statement_start_offset / 2 ) < 0 THEN 0
ELSE CASE WHEN er.statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(MAX),
qt.text)) * 2
ELSE er.statement_end_offset END - er.statement_start_offset / 2 END ),
STATUS = ses.STATUS,
[Login] = ses.login_name,
Host = ses.host_name,
DBName = DB_Name(er.database_id),
StartTime = er.start_time,
Protocol = con.net_transport,
transaction_isolation = CASE ses.transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'Read Uncommitted'
WHEN 2 THEN 'Read Committed'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END,
ConnectionWrites = con.num_writes ,ConnectionReads = con.num_reads,

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 will provide most memory and IO


SELECT TOP 10
ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' +
OBJECT_NAME(qt.objectid, qt.dbid)
,DiskReads = qs.total_physical_reads --The_worst_reads, disk_reads
,MemoryReads = qs.total_logical_reads --Logical_Reads_are_memory_reads
,ReadsPerExecution = NULLIF(qs.total_physical_reads + qs.total_logical_reads,0) /
qs.execution_count
,Executions = qs.execution_count
,CPUTime = qs.total_worker_time
,DiskWaitAndCPUTime = qs.total_elapsed_time
,MemoryWrites = qs.max_logical_writes
,DateCached = qs.creation_time
,DatabaseName = DB_Name(qt.dbid)
,LastExecutionTime = qs.last_execution_time
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
ORDER BY qs.total_physical_reads + qs.total_logical_reads 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)

create table #dbsize


(Dbname sysname,dbstatus varchar(50),Recovery_Model varchar(40) default ('NA'),
file_Size_MB decimal(30,2)default (0),Space_Used_MB decimal(30,2)default
(0),Free_Space_MB decimal(30,2) default (0))
go

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'

create table #logsize


(Dbname sysname, Log_File_Size_MB decimal(38,2)default (0),log_Space_Used_MB
decimal(30,2)default (0),log_Free_Space_MB decimal(30,2)default (0))
go

create table #dbfreesize (name sysname,


database_size varchar(50),
Freespace varchar(50) default (0.00))
go

create table #alldbstate


(dbname sysname,
DBstatus varchar(55),
R_model Varchar(30))
go

insert into #logsize(Dbname,Log_File_Size_MB,log_Space_Used_MB,log_Free_Space_MB)


exec sp_msforeachdb
'use [?];
select DB_NAME() AS DbName,
sum(size)/128.0 AS Log_File_Size_MB,
sum(CAST(FILEPROPERTY(name, ''SpaceUsed'') AS INT))/128.0 as log_Space_Used_MB,
SUM( size)/128.0 - sum(CAST(FILEPROPERTY(name,''SpaceUsed'') AS INT))/128.0 AS
log_Free_Space_MB
from sys.database_files where type=1 group by type'

8
CITOSS (FTP-PASS) SQL DBA queries

if exists (select * from tempdb.sys.all_objects where name like '%#dbfreesize%')

insert into #dbfreesize (name,database_size,Freespace)


exec sp_msforeachdb
'use [?];SELECT database_name = db_name()
,database_size = ltrim(str((convert(DECIMAL(15, 2), dbsize) +
convert(DECIMAL(15, 2), logsize)) * 8192 / 1048576, 15, 2) + ''MB'')
,''unallocated space'' = ltrim(str((
CASE
WHEN dbsize >= reservedpages
THEN (convert(DECIMAL(15, 2), dbsize) -
convert(DECIMAL(15, 2), reservedpages)) * 8192 / 1048576
ELSE 0
END
), 15, 2) + '' MB'')
FROM (
SELECT dbsize = sum(convert(BIGINT, CASE
WHEN type = 0
THEN size
ELSE 0
END))
,logsize = sum(convert(BIGINT, CASE
WHEN type <> 0
THEN size
ELSE 0
END))
FROM sys.database_files
) AS files
,(
SELECT reservedpages = sum(a.total_pages)
,usedpages = sum(a.used_pages)
,pages = sum(CASE
WHEN it.internal_type IN (202,204,211,212,213,214,215,216)
THEN 0
WHEN a.type <> 1
THEN a.used_pages
WHEN p.index_id < 2
THEN a.data_pages
ELSE 0
END)
FROM sys.partitions p
INNER JOIN sys.allocation_units a
ON p.partition_id = a.container_id
LEFT JOIN sys.internal_tables it
ON p.object_id = it.object_id
) AS partitions'

if exists (select * from tempdb.sys.all_objects where name like '%#alldbstate%')

--select * from sys.master_files

insert into #alldbstate (dbname,DBstatus,R_model)


select
name,CONVERT(varchar(20),DATABASEPROPERTYEX(name,'status')),recovery_model_desc
from sys.databases

9
CITOSS (FTP-PASS) SQL DBA queries

--select * from #dbsize

insert into #dbsize(Dbname,dbstatus,Recovery_Model)


select dbname,dbstatus,R_model from #alldbstate where DBstatus <> 'online'

insert into #logsize(Dbname)


select dbname from #alldbstate where DBstatus <> 'online'

insert into #dbfreesize(name)


select dbname from #alldbstate where DBstatus <> 'online'

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

drop table #logsize


drop table #dbsize
drop table #alldbstate
drop table #dbfreesize

create table #ls (name varchar(255), LogSize real, LogSpaceUsed real, Status int)

insert #ls exec ('dbcc sqlperf(logspace)')

declare @name varchar(255), @sql varchar(1000);

select d.name, DATABASEPROPERTYEX(d.name, 'Status') Status,


case when DATABASEPROPERTYEX(d.name, 'IsAutoCreateStatistics') = 1
then 'ON' else 'OFF' end AutoCreateStatistics,
case when DATABASEPROPERTYEX(d.name, 'IsAutoUpdateStatistics') = 1
then 'ON' else 'OFF' end AutoUpdateStatistics,
case when DATABASEPROPERTYEX(d.name, 'IsAutoShrink') = 1
then 'ON' else 'OFF' end AutoShrink,
case when DATABASEPROPERTYEX(d.name, 'IsAutoClose') = 1
then 'ON' else 'OFF' end AutoClose,
DATABASEPROPERTYEX(d.name, 'Collation') Collation,
DATABASEPROPERTYEX(d.name, 'Updateability') Updateability,
DATABASEPROPERTYEX(d.name, 'UserAccess') UserAccess,
replace(page_verify_option_desc, '_', ' ') PageVerifyOption,
d.compatibility_level CompatibilityLevel,
DATABASEPROPERTYEX(d.name, 'Recovery') RecoveryModel,
convert(bigint, 0) as Size, convert(bigint, 0) Used,
case when sum(NumberReads+NumberWrites) > 0
then sum(IoStallMS)/sum(NumberReads+NumberWrites) else -1 end AvgIoMs,
ls.LogSize, ls.LogSpaceUsed,
b.backup_start_date LastBackup
into #dbs1
from master.sys.databases as d
left join msdb..backupset b
on d.name = b.database_name and b.backup_start_date = (
select max(backup_start_date)

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;

create table #dbsize1 (


fileid int,
filegroup int,
TotalExtents bigint,
UsedExtents bigint,
dbname varchar(255),
FileName varchar(255));

declare c1 cursor for select name from #dbs1;


open c1;

fetch next from c1 into @name;


while @@fetch_status = 0
begin
set @sql = 'use [' + @name + ']; DBCC SHOWFILESTATS WITH NO_INFOMSGS;'
insert #dbsize1 exec(@sql);
update #dbs1
set Size = (select sum(TotalExtents) / 16 from #dbsize1),
Used = (select sum(UsedExtents) / 16 from #dbsize1)
where name = @name;
truncate table #dbsize1;
fetch next from c1 into @name;
end;
close c1;
deallocate c1;

select * from #dbs1


order by name;

drop table #dbsize1;


drop table #dbs1;
drop table #ls;

11
CITOSS (FTP-PASS) SQL DBA queries

12

You might also like