Scripts 1
Scripts 1
Scripts 1
We can learn that all databases CPU resources usage with following script.
WITH DB_CPU_STATS_ON_INSTANCE
AS
FROM sys.dm_exec_query_stats AS qs
FROM sys.dm_exec_plan_attributes(qs.plan_handle)
GROUP BY DatabaseID)
DatabaseName, [CPU_Time_Ms],
FROM DB_CPU_STATS_ON_INSTANCE
You can find TOP CPU queries in SQL Server database with following query.
SELECT TOP 50
,Executions = qs.execution_count
,TotalCPUTime = qs.total_worker_time
,AverageCPUTime = qs.total_worker_time/qs.execution_count
,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
You can find TOP CPU queries in SQL Server database with following query.
select top 50
query_stats.query_hash,
min(query_stats.statement_text) as QUERY
from (
select qs.*,
SUBSTRING(st.text,(qs.statement_start_offset/2)+1,
((case statement_end_offset
from sys.dm_exec_query_stats as qs
) as query_stats
group by query_stats.query_hash
order by 2 desc;
You can find TOP 50 IO queries in SQL Server database with following query.
select
q.[text],
SUBSTRING(q.text, (highest_cpu_queries.statement_start_offset/2)+1,
((CASE highest_cpu_queries.statement_end_offset
ELSE highest_cpu_queries.statement_end_offset
highest_cpu_queries.total_worker_time,
highest_cpu_queries.total_logical_reads,
highest_cpu_queries.last_execution_time,
highest_cpu_queries.execution_count,
q.dbid,
q.objectid,
q.number,
q.encrypted,
highest_cpu_queries.plan_handle
from
(select top 50
qs.last_execution_time,
qs.execution_count,
qs.plan_handle,
qs.total_worker_time,
qs.statement_start_offset,
qs.statement_end_offset,
qs.total_logical_reads
from
sys.dm_exec_query_stats qs
You can find TOP IO queries in SQL Server database with following query.
select
SUBSTRING(st.text,(qs.statement_start_offset/2)+1,
((case statement_end_offset
qs.total_logical_reads,
qs.total_physical_reads,
qs.execution_count
from sys.dm_exec_query_stats as qs
To see IO stats and following information you can execute below script.
select
serverproperty('MachineName') 'machine_name'
,isnull(serverproperty('InstanceName'),'mssqlserver') 'instance_name'
,@@SERVERNAME 'sql_server_name'
,DB_NAME(mf.database_id) 'database_name'
,mf.name 'logical_name'
,mf.physical_name 'physical_name'
,left(mf.physical_name,1) 'disk_drive'
,mf.type_desc 'file_type'
,mf.state_desc 'state'
,case mf.is_read_only
end 'read_only'
,convert(numeric(18,2),convert(numeric,mf.size)*8/1024) 'size_mb'
,divfs.size_on_disk_bytes/1024/1024 'size_on_disk_mb'
,case mf.is_percent_growth
end 'growth'
,case mf.is_percent_growth
end 'next_growth_mb'
,case mf.max_size
when -1 then (case mf.growth when 0 then 'NO-growth' else 'unlimited' end)
end 'max_size'
,divfs.num_of_reads
,divfs.num_of_bytes_read/1024/1024 'read_mb'
,divfs.io_stall_read_ms
,divfs.num_of_writes
,divfs.num_of_bytes_written/1024/1024 'write_mb'
,divfs.io_stall_write_ms
from sys.master_files as mf
select text,
SUBSTRING(st.text, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
ELSE qs.statement_end_offset
* from sys.dm_exec_requests qs
SELECT
db.name DBName,
tl.request_session_id,
wt.blocking_session_id,
OBJECT_NAME(p.OBJECT_ID) BlockedObjectName,
tl.resource_type,
h1.TEXT AS RequestingText,
h2.TEXT AS BlockingTest,
tl.request_mode
FROM sys.dm_tran_locks AS tl
GO
Backup Check
Backup should be checked everyday by SQL Server DBA with following script.
SELECT DB.name AS Database_Name
,MAX(DB.recovery_model_desc) AS Recovery_Model
,MAX(BS.backup_start_date) AS Last_Backup
AS Last_Full_backup
THEN 1 END)
AS Count_Full_backup
AS Last_Log_backup
THEN 1 END)
AS Count_Log_backup
AS Last_Differential_backup
THEN 1 END)
AS Count_Differential_backup
AS LastFile
,SUM(CASE WHEN BS.type = 'F'
THEN 1 END)
AS CountFile
AS LastFileDiff
THEN 1 END)
AS CountFileDiff
AS LastPart
THEN 1 END)
AS CountPart
AS LastPartDiff
THEN 1 END)
AS CountPartDiff
FROM sys.databases AS DB
LEFT JOIN
msdb.dbo.backupset AS BS
ON BS.database_name = DB.name
GROUP BY DB.name
select @db=DB_ID('DEVECI')
select 'ALTER INDEX [' + i.name +'] on '+OBJECT_NAME(s.object_id)+' REBUILD WITH (ONLINE
= ON)',
objname = OBJECT_NAME(s.object_id),
s.object_id,
index_name= i.name,
index_type_desc,
avg_fragmentation_in_percent
from sys.dm_db_index_physical_stats(@db,null,null,null,null) as s
where avg_fragmentation_in_percent>30
You can find all indexes usage statistic with following script.
s.object_id,
index_name= i.name,
index_id = i.index_id,
from sys.dm_db_index_usage_stats as s
and OBJECTPROPERTY(s.object_id,'IsUserTable')=1
SELECT
object_name(si.[object_id]) AS [TableName]
, CASE
ELSE 'Text/Image'
END AS [IndexType]
, si.[name] AS [IndexName]
, si.[stats_id] AS [IndexID]
, CASE
WHEN si.[stats_id] BETWEEN 1 AND 250 AND STATS_DATE (si.[object_id], si.[stats_id]) <
DATEADD(m, -1, getdate())
WHEN si.[stats_id] BETWEEN 1 AND 250 AND STATS_DATE (si.[object_id], si.[stats_id]) <
DATEADD(wk, -1, getdate())
ELSE ''
END AS [Warning]
, no_recompute
FROM sys.stats AS si
go
SELECT
SPID = er.session_id
,BlkBy = er.blocking_session_id
,ElapsedMS = er.total_elapsed_time
,CPU = er.cpu_time
,IOWrites = er.writes
,Executions = ec.execution_count
,CommandType = er.command
,SQLStatement =
SUBSTRING
qt.text,
er.statement_start_offset/2,
ELSE er.statement_end_offset
END - er.statement_start_offset)/2
,Status = ses.status
,[Login] = ses.login_name
,Host = ses.host_name
,DBName = DB_Name(er.database_id)
,LastWaitType = er.last_wait_type
,StartTime = er.start_time
,Protocol = con.net_transport
,transaction_isolation =
CASE ses.transaction_isolation_level
END
,ConnectionWrites = con.num_writes
,ConnectionReads = con.num_reads
,ClientAddress = con.client_net_address
,Authentication = con.auth_scheme
FROM sys.dm_exec_requests er
OUTER APPLY
FROM sys.dm_exec_cached_plans cp
) ec
ORDER BY
er.blocking_session_id DESC,
er.session_id;
from sys.dm_os_waiting_tasks wt
where s.is_user_process=1
,waiting_tasks_count
FROM sys.dm_os_wait_stats
'BROKER_TRANSMITTER','CHECKPOINT_QUEUE','CHKPT,CLR_AUTO_EVENT','CLR_MANUAL_EVENT','KSOUR
CE_WAKEUP','LAZYWRITER_SLEEP',
'LOGMGR_QUEUE','ONDEMAND_TASK_QUEUE','REQUEST_FOR_DEADLOCK_SEARCH','RESOURCE_QUEUE','SER
VER_IDLE_CHECK',
'SLEEP_BPOOL_FLUSH','SLEEP_DBSTARTUP','SLEEP_DCOMSTARTUP','SLEEP_MSDBSTARTUP','SLEEP_SYS
TEMTASK','SLEEP_TASK',
'SLEEP_TEMPDBSTARTUP','SNI_HTTP_ACCEPT','SQLTRACE_BUFFER_FLUSH','TRACEWRITE','WAIT_FOR_R
ESULTS','WAITFOR_TASKSHUTDOWN',
'XE_DISPATCHER_WAIT','XE_TIMER_EVENT','WAITFOR')
ORDER BY 4 DESC
with waits as
(select
wait_type,
waiting_tasks_count as waitcount,
from sys.dm_os_wait_stats
N'CLR_SEMAPHORE', N'LAZYWRITER_SLEEP',
N'RESOURCE_QUEUE', N'SQLTRACE_BUFFER_FLUSH',
N'SLEEP_TASK', N'SLEEP_SYSTEMTASK',
N'WAITFOR', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
N'CHECKPOINT_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH',
N'XE_TIMER_EVENT', N'XE_DISPATCHER_JOIN',
N'LOGMGR_QUEUE', N'FT_IFTS_SCHEDULER_IDLE_WAIT',
N'BROKER_TASK_STOP', N'CLR_MANUAL_EVENT',
N'CLR_AUTO_EVENT', N'DISPATCHER_QUEUE_SEMAPHORE',
N'TRACEWRITE', N'XE_DISPATCHER_WAIT',
N'BROKER_TO_FLUSH', N'BROKER_EVENTHANDLER',
N'FT_IFTSHC_MUTEX', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
N'DIRTY_PAGE_POLL', N'SP_SERVER_DIAGNOSTICS_SLEEP')
select
w1.wait_type as waittype,
w1.waitcount wait_count,
from waits as w1
SELECT PVT.DatabaseName
FROM
FROM msdb.dbo.backupset as BS
INNER JOIN
msdb.dbo.backupfile AS BF
ON BS.backup_set_id = BF.backup_set_id
GROUP BY BS.database_name
PIVOT (SUM(BCKSTAT.AvgSizeMB)
FOR BCKSTAT.MonthsAgo IN ([0], [-1], [-2], [-3], [-4], [-5], [-6], [-7], [-8], [-9], [-
10], [-11], [-12])
) AS PVT
ORDER BY PVT.DatabaseName;
Partitioning Check
You can check if table is partitioned in SQL Server with following query.
select distinct
pp.[object_id],
TbName = OBJECT_NAME(pp.[object_id]),
index_name = i.[name],
index_type_desc = i.type_desc,
partition_scheme = ps.[name],
data_space_id = ps.data_space_id,
function_name = pf.[name],
function_id = ps.function_id
from sys.partitions pp
on pp.[object_id] = i.[object_id]
on i.data_space_id = ds.data_space_id
inner join sys.partition_schemes ps
on ds.data_space_id = ps.data_space_id
on ps.function_id = pf.function_id
Inventory Collection Script
Inventory Collect Query is like following, it will make your job very simplify when you connect to any SQL
Server database for the first time.
,serverproperty('MachineName') 'Machine_Name'
,isnull(serverproperty('InstanceName'),'mssqlserver') 'Instance_Name'
,@@SERVERNAME 'Sql_Server_Name'
,SERVERPROPERTY('productversion') Product_Version
,d.name 'database_name'
,suser_sname(d.owner_sid) 'owner'
,ls.cntr_value as [log_size_kb]
,lu.cntr_value as [log_used_kb]
,lp.cntr_value as [percent_log_used]
,ds.cntr_value as [data_files_size_kb]
from sys.databases d
order by d.name;
Query is like following, it will make your job very simplify when you connect to any SQL Server database for
the first time.
select
serverproperty('MachineName') 'machine_name'
,isnull(serverproperty('InstanceName'),'mssqlserver') 'instance_name'
,@@SERVERNAME 'sql_server_name'
,d.name 'database_name'
,suser_sname(d.owner_sid) 'owner'
,d.compatibility_level
,d.collation_name
,d.is_auto_close_on
,d.is_auto_shrink_on
,d.state_desc
,d.snapshot_isolation_state
,d.is_read_committed_snapshot_on
,d.recovery_model_desc
,d.is_auto_create_stats_on
,d.is_auto_update_stats_on
,d.is_auto_update_stats_async_on
,d.is_in_standby
,d.page_verify_option_desc
,d.log_reuse_wait_desc
from sys.databases d
order by d.name
Inventory Collect Query is like following, it will make your job very simplify when you connect to any SQL
Server database for the first time.
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
GO
RECONFIGURE;
GO
/*******************************************************/
SET NOCOUNT ON
CREATE TABLE #drives (drive char(1) PRIMARY KEY, FreeSpace int NULL,
@fso
WHILE @@FETCH_STATUS=0
BEGIN
sp_OAGetProperty
End
Close dcur
DEALLOCATE dcur
--SELECT @@Servername
--SELECT
--ORDER BY drive
( Logical_CPU_Count bigint,
Hyperthread_Ratio bigint,
Physical_CPU_Count bigint,
Physical_Memory_MB bigint
Logical_CPU_Count,
Hyperthread_Ratio,
Physical_CPU_Count,
Physical_Memory_MB
SELECT
cpu_count AS [Logical_CPU_Count]
,hyperthread_ratio AS [Hyperthread_Ratio]
,cpu_count/hyperthread_ratio AS [Physical_CPU_Count]
, physical_memory_kb/1024 AS [Physical_Memory_MB]
FROM sys.dm_os_sys_info
( Machine_Name varchar(50),
Instance_Name varchar(50),
Sql_Server_Name varchar(50),
Total_Database_log_size_MB bigint,
Total_Database_log_used_MB bigint,
Total_Database_Data_File_Size_MB bigint
)
INSERT INTO #DatabaseInfo
Machine_Name,
Instance_Name,
Sql_Server_Name,
Total_Database_log_size_MB,
Total_Database_log_used_MB,
Total_Database_Data_File_Size_MB
,convert(varchar(50),isnull(serverproperty('InstanceName'),'mssqlserver'))
'Instance_Name'
,convert(varchar(50),@@SERVERNAME) 'Sql_Server_Name'
,sum(ls.cntr_value/1024) as [Total_Database_log_size_MB]
,sum(lu.cntr_value/1024)as [Total_Database_log_used_MB]
,sum(ds.cntr_value/1024) as [Total_Database_Data_File_Size_MB]
from sys.databases d
WITH SizeDisc AS
SUM(FreeSpace) as 'TotalFreeDiscSizeOnServer(MB)'
FROM #drives
SELECT *
FROM #DatabaseInfo,#CPUInfo,SizeDisc
GO
/*******************************************************/
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 0;
GO
RECONFIGURE;
/*******************************************************/
GO