All Scripts
All Scripts
-----------------
Exec sp_help_revlogin
Login Details:
---------------
select *from sys.syslogins
SELECT st.session_id ,
st.is_user_transaction ,
dt.database_transaction_begin_time ,
dt.database_transaction_log_record_count ,
dt.database_transaction_log_bytes_used
FROM sys.dm_tran_session_transactions st
JOIN sys.dm_tran_database_transactions dt
ON st.transaction_id = dt.transaction_id
AND dt.database_id = DB_ID('')
WHERE st.session_id = 56
SELECT dm_ws.wait_duration_ms,
dm_ws.wait_type,
dm_es.status,
dm_t.TEXT,
dm_qp.query_plan,
dm_ws.session_ID,
dm_es.cpu_time,
dm_es.memory_usage,
dm_es.logical_reads,
dm_es.total_elapsed_time,
dm_es.program_name,
DB_NAME(dm_r.database_id) DatabaseName,
-- Optional columns
dm_ws.blocking_session_id,
dm_r.wait_resource,
dm_es.login_name,
dm_r.command,
dm_r.last_wait_type
FROM sys.dm_os_waiting_tasks dm_ws
INNER JOIN sys.dm_exec_requests dm_r ON dm_ws.session_id = dm_r.session_id
INNER JOIN sys.dm_exec_sessions dm_es ON dm_es.session_id = dm_r.session_id
CROSS APPLY sys.dm_exec_sql_text (dm_r.sql_handle) dm_t
CROSS APPLY sys.dm_exec_query_plan (dm_r.plan_handle) dm_qp
WHERE dm_es.is_user_process = 1
GO
SELECT
[Spid] = [er]. [session_Id] ,
[sp] .[Ecid] ,
[Database] = DB_NAME ([sp]. [dbid]) ,
[User] = [sp]. [nt_username] ,
[Status] = [er]. [status] ,
[Wait] = [er]. [wait_type] ,
[er] .[Start_time] ,
[er] .[Cpu_time] ,
[er] .[Total_elapsed_time],
[Individual Query] = 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]
END-[er] .[statement_start_offset] )/2) ,
[Parent Query] = [qt]. [text] ,
Program = [sp]. [program_name] ,
[er] .[Command] ,
[sp] .[Hostname] ,
[sp] .[Nt_domain]
FROM
[sys] .[dm_exec_requests] er
INNER JOIN [sys].[sysprocesses] sp
ON [er]. [session_id]=[sp] .[spid]
CROSS APPLY [sys].[dm_exec_sql_text] ([er]. [sql_handle]) AS qt
WHERE
[er] .[session_Id]> 50 -- Ignore system spids.
AND [er]. [session_Id] NOT IN ( @@SPID ) -- Ignore this current
statement.
ORDER BY [er].[session_Id] ,[sp]. [ecid]
Missing Index :
---------------
SELECT
er.session_id,
er.blocking_session_id,
er.start_time,
er.status,
dbName = DB_NAME(er.database_id),
er.wait_type,
er.wait_time,
er.last_wait_type,
er.granted_query_memory,
er.reads,
er.logical_reads,
er.writes,
er.row_count,
er.total_elapsed_time,
er.cpu_time,
er.open_transaction_count,
er.open_transaction_count,
s.text,
qp.query_plan,
logDate = CONVERT(DATE,GETDATE()),
logTime = CONVERT(TIME,GETDATE())
FROM sys.dm_exec_requests er
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) s
CROSS APPLY sys.dm_exec_query_plan(er.plan_handle) qp
WHERE
CONVERT(VARCHAR(MAX), qp.query_plan) LIKE '%<missing%'
GO
;with CTE as (
SELECT b.name as job_name, a.start_execution_date, a.stop_execution_date,
datediff(minute, a.start_execution_date, a.stop_execution_date) as run_time
FROM msdb.dbo.sysjobactivity a
join msdb.dbo.sysjobs b
on a.job_id = b.job_id
WHERE a.start_execution_date > DATEADD(dd, -7, GETDATE()) -- date criteria
and datediff(minute, a.start_execution_date, a.stop_execution_date) > 5 --
runtime criteria
and a.run_requested_source = 1 -- scheduler only
)
select a.job_name, a.start_execution_date, a.run_time, b.job_name,
b.start_execution_date, b.run_time
from CTE a, CTE b
where a.start_execution_date between b.start_execution_date and
b.stop_execution_date
and a.job_name <> b.job_name
and (a.start_execution_date > b.start_execution_date or a.stop_execution_date
between b.start_execution_date and b.stop_execution_date)
;
SELECT TOP ( 240 ) /* Set the number of minutes history that you want here */
@@servername AS [Servername] ,
DATEADD(ms, -1 * ( @ts_now - [timestamp] ), GETDATE()) AS [Sample Time] ,
SQLProcessUtilisation
INTO #Data
FROM ( SELECT [R].[sample].[value]('(./Record/@id)[1]', 'int') AS [record_id]
,
[R].[sample].[value]('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]',
'int') AS [SystemIdle] ,
[R].[sample].[value]('(./Record/SchedulerMonitorEvent/SystemHealth/
ProcessUtilization)[1]',
'int') AS [SQLProcessUtilisation] ,
[timestamp]
FROM ( SELECT [timestamp] ,
CONVERT(XML, record) AS [sample]
FROM [sys].[dm_os_ring_buffers] AS DORB
WHERE [ring_buffer_type] =
N'RING_BUFFER_SCHEDULER_MONITOR'
AND [record] LIKE N'%<SystemHealth>%'
) AS [R]
) AS y
ORDER BY [record_id] DESC;
WITH datas
AS ( SELECT ROW_NUMBER() OVER ( ORDER BY [Sample Time] ) AS r_n ,
[SQLProcessUtilisation]
FROM [#Data] AS D
)
SELECT 10 AS [Last n minutes range] ,
AVG([SQLProcessUtilisation]) AS [Avg SQL CPU] ,
MIN([SQLProcessUtilisation]) AS [Min SQL CPU] ,
MAX([SQLProcessUtilisation]) AS [Max SQL CPU]
FROM [datas]
WHERE [r_n] < 11
UNION
SELECT 30 ,
AVG([SQLProcessUtilisation]) ,
MIN([SQLProcessUtilisation]) ,
MAX([SQLProcessUtilisation])
FROM [datas]
WHERE [r_n] < 31
UNION
SELECT 60 ,
AVG([SQLProcessUtilisation]) ,
MIN([SQLProcessUtilisation]) ,
MAX([SQLProcessUtilisation])
FROM [datas]
WHERE [r_n] < 61
UNION
SELECT 120 ,
AVG([SQLProcessUtilisation]) ,
MIN([SQLProcessUtilisation]) ,
MAX([SQLProcessUtilisation])
FROM [datas]
WHERE [r_n] < 121
UNION
SELECT 240 ,
AVG([SQLProcessUtilisation]) ,
MIN([SQLProcessUtilisation]) ,
MAX([SQLProcessUtilisation])
FROM [datas];
SELECT TOP 5
[LogDate]
,SUBSTRING([TEXT], CHARINDEX(') is ', [TEXT]) + 4,CHARINDEX(' complete (',
[TEXT]) - CHARINDEX(') is ', [TEXT]) - 4) AS PercentComplete
,CAST(SUBSTRING([TEXT], CHARINDEX('approximately', [TEXT]) + 13,CHARINDEX('
seconds remain', [TEXT]) - CHARINDEX('approximately', [TEXT]) - 13) AS FLOAT)/60.0
AS MinutesRemaining
,CAST(SUBSTRING([TEXT], CHARINDEX('approximately', [TEXT]) + 13,CHARINDEX('
seconds remain', [TEXT]) - CHARINDEX('approximately', [TEXT]) - 13) AS
FLOAT)/60.0/60.0 AS HoursRemaining
,[TEXT]
/*------------------------------------------------------------------------------+
#| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : |
#|{>/------------------------------------------------------------------------\<}|
#|: | Description:This script return top queries taxing sql server CPU's|
#|: | |
#|: | |
#|{>\------------------------------------------------------------------------/<}|
#| = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = : = :|
# Detect worst performing sql queries which is slowing down Microsoft SQL Server,
this script return top queries taxing sql server CPUs. |
#+-----------------------------------------------------------------------------*/
use tempdb
go
GO
, @FilterMoreThanMiliSeconds bigint = 1
, @FilterHours bigint = 2
, @execution_count bigint = 2
, @debugFlg bit = 0
,isnull(db_name(QueryText.dbid),'PreparedSQL') as DBName
,SUBSTRING(QueryText.text, (QueryStats.statement_start_offset/2)+1,
(isnull((
CASE QueryStats.statement_end_offset
ELSE QueryStats.statement_end_offset
END - QueryStats.statement_start_offset),0)/2)
+ 1) AS QueryExecuted
,total_worker_time AS total_worker_time
,QueryStats.execution_count as execution_count
,statement_start_offset,statement_end_offset
,query_hash
,plan_handle
,sql_handle
into ##FindTopCPUQueries_set1
where QueryStats.query_hash IN
select QueryStatsBaseTable.query_hash
select
into ##FindTopCPUQueries_set2
from ##FindTopCPUQueries_set1
group by query_hash,servername,runtime
SELECT
SCHEMA_NAME(o.schema_id) + '.' + OBJECT_NAME(p.object_id) AS NAME,
SUM(reserved_page_count) * 8 AS total_space_used_kb,
SUM(CASE WHEN index_id < 2 THEN reserved_page_count ELSE 0 END ) * 8 AS
table_space_used_kb,
SUM(CASE WHEN index_id > 1 THEN reserved_page_count ELSE 0 END ) * 8 AS
nonclustered_index_spaced_used_kb,
MAX(row_count) AS row_count
FROM
sys.dm_db_partition_stats AS p
INNER JOIN sys.all_objects AS o ON p.object_id = o.object_id
WHERE
o.is_ms_shipped = 0
GROUP BY
SCHEMA_NAME(o.schema_id) + '.' + OBJECT_NAME(p.object_id)
ORDER BY
NAME
select B.name,CONVERT(numeric(30,3),(CONVERT(float,
SUM(A.used_page_count)*8)/1024)) as [Table Used Size(MB)],
CONVERT(numeric(30,3),(CONVERT(float, SUM(A.reserved_page_count)*8)/1024)) as
[Table Located Size(MB)],
(CONVERT(numeric(30,3),(CONVERT(float, SUM(A.reserved_page_count)*8)/1024)) -
CONVERT(numeric(30,3),(CONVERT(float, SUM(A.used_page_count)*8)/1024))) as [Table
Free Size(MB)] ,
A.row_count
into #temp_table1
from sys.dm_db_partition_stats as A, sys.all_objects as B
where A.object_id = B.object_id and B.type != 'S'
group by name,row_count
order by B.name asc
USE [MASTER]
GO
IF @dbid IS NULL
BEGIN
PRINT @DatabaseName + ' not found on current SQL instance.'
GOTO EndProcess
END
--Kill processes
SET @Cursor = CURSOR FOR
SELECT
ProcessID,
LoginName
FROM
@ProcessDetails
OPEN @Cursor
FETCH NEXT FROM @Cursor INTO
@ProcID,
@User
WHILE (@@FETCH_STATUS = 0)
BEGIN
END
CLOSE @Cursor
DEALLOCATE @Cursor
--End information
EndProcess:
PRINT ''
PRINT @Info + ' processes killed.'
PRINT ''
PRINT 'Script End'
USE master
GO
SET NOCOUNT ON
DECLARE @Kb float
DECLARE @PageSize float
DECLARE @SQL varchar(2000)
SELECT
DatabaseName = fsi.DatabaseName,
FileGroupName = fsi.FileGroupName,
LogicalName = RTRIM(fsi.LogicalName),
FileName = RTRIM(fsi.FileName),
FileSize = CAST(fsi.FileSize*@PageSize/@Kb as decimal(15,2)),
UsedSpace = CAST(ISNULL((fs.UsedExtents*@PageSize*8.0/@Kb),
fsi.FileSize*@PageSize/@Kb * ls.SpaceUsedPercent/100.0) as decimal(15,2)),
FreeSpace = CAST(ISNULL(((fsi.FileSize - UsedExtents*8.0)*@PageSize/@Kb),
(100.0-ls.SpaceUsedPercent)/100.0 * fsi.FileSize*@PageSize/@Kb) as decimal(15,2)),
[FreeSpace %] = CAST(ISNULL(((fsi.FileSize - UsedExtents*8.0) / fsi.FileSize
* 100.0), 100-ls.SpaceUsedPercent) as decimal(15,2))
FROM #FileSize fsi
LEFT JOIN #FileStats fs
ON fs.FileName = fsi.FileName
LEFT JOIN #LogSpace ls
ON ls.DatabaseName = fsi.DatabaseName
ORDER BY 1,3
USE tempdb;
declare @dbname varchar(50);
set @dbname = 'Tempdb' -- Change db name
-- Get free space usage stats within a db at file level for a SQL Server Instance
CREATE TABLE #tmpFileSize (
Database_Name VARCHAR(200),
LogicalFileName VARCHAR(200),
Filepath VARCHAR(200),
FileSize_MB DECIMAL(12, 2),
FileSize_GB DECIMAL(12, 2),
SpaceUsed_MB DECIMAL(12, 2),
FreeSpace_MB DECIMAL(12, 2),
FreeSpace_GB decimal(12,2)
)
-- Update GB Size
Update #tmpFileSize
set FileSize_GB = FileSize_MB/1024,
Freespace_GB = FreeSpace_MB/1024
SELECT *
FROM #tmpFilesize tfs
WHERE tfs.database_Name = @dbname --Remove from here
union All
select @dbname,
'Total',
'',
Sum(FileSize_MB),
SUM(FileSize_GB),
Sum(SpaceUsed_MB),
Sum(FreeSpace_MB),
Sum(freeSpace_GB)
From #tmpFilesize tfs
where tfs.Database_name = @dbname --
EXEC sp_MSForEachDB
'USE ?;
SELECT DB_NAME(), ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE ''%foobar%''
AND ROUTINE_TYPE = ''PROCEDURE'''
Script to find the total used size of all database inside SQL Server:
---------------------------------------------------------------------
CLOSE curDB
DEALLOCATE curDB
select SUM(used_mb) from #dbusedsize
drop table #dbusedsize
USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
select
S.[host_name],
DB_NAME(R.database_id) as [database_name],
(CASE WHEN S.program_name like 'SQLAgent - TSQL JobStep (Job %' THEN j.name
ELSE S.program_name END) as Name ,
S.login_name, R.status, R.command
,b.text, R.blocking_session_id, R.percent_complete, R.session_id
, R.wait_type,R.wait_time,
isnull(DATEDIFF(mi, S.last_request_start_time, getdate()), 0) [MinutesRunning]
,qp.query_plan
FROM sys.dm_exec_requests R with (nolock)
INNER JOIN sys.dm_exec_sessions S with (nolock)
ON R.session_id = S.session_id
OUTER APPLY sys.dm_exec_sql_text(R.sql_handle) b
OUTER APPLY sys.dm_exec_query_plan (R.plan_handle) AS qp
LEFT OUTER JOIN msdb.dbo.sysjobs J with (nolock)
ON (substring(left(j.job_id,8),7,2) +
substring(left(j.job_id,8),5,2) +
substring(left(j.job_id,8),3,2) +
substring(left(j.job_id,8),1,2)) = substring(S.program_name,32,8)
WHERE R.session_id > 50
and R.session_id <> @@SPID
and S.[host_name] IS NOT NULL
ORDER BY s.[host_name],S.login_name;
/************************************************************************
*************************************************************************
** The following script will show you
**
** If there are any open transactions running on your database. **
** While running the below query if you find any query which **
** While running the below query if you find any query which **
** is running for long time it can be killed using following command **
** KILL [session_id]
**
** you could also open the query window and use the following command **
** RollBack Transaction
**
*************************************************************************
************************************************************************/
DECLARE @databasename NVARCHAR(MAX)
use master
go
select b.name DB_Name, a.name Logical_name, a.filename File_Name,
cast((a.size * 8.00) / 1024 as numeric(12,2)) as DB_Size_in_MB,
case when a.growth > 100 then 'In MB' else 'In Percentage' end File_Growth,
cast(case when a.growth > 100 then (a.growth * 8.00) / 1024
else (((a.size * a.growth) / 100) * 8.00) / 1024
end as numeric(12,2)) File_Growth_Size_in_MB,
case when ( maxsize = -1 or maxsize=268435456 ) then 'AutoGrowth Not Restricted'
else 'AutoGrowth Restricted' end AutoGrowth_Status
from sysaltfiles a
join sysdatabases b on a.dbid = b.dbid
where DATABASEPROPERTYEX(b.name, 'status') = 'ONLINE'
order by b.name
FROM sys.objects so
LEFT JOIN LastActivity la
on so.object_id = la.ObjectID
LEFT JOIN sys.tables st
on so.object_id = st.object_id
LEFT JOIN sys.views sv
on so.object_id = sv.object_id
GROUP BY OBJECT_NAME(so.object_id)
, so.type
,st.create_date
,st.modify_date
,sv.create_date
,sv.modify_date
ORDER BY OBJECT_NAME(so.object_id)
Use msdb
go
SELECT name,
step_id
,run_date
,count(*) howMany
,min((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 + 31
) / 60) lowest_Min
,avg((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 + 31
) / 60) average_Min
,max((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 + 31
) / 60) highest_Min
,stdev((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 +
31 ) / 60) stdev_Min
from sysJobHistory h
inner join sysjobs j on
(h.job_id = j.job_id)
where name =''
group by name, step_id, run_date
order by run_date desc
SELECT
DatabaseRestoredTo = RH.destination_database_name,
TimeOfRestore = RH.restore_date,
UserImplimentingRestore = RH.user_name,
RestoreType = CASE RH.restore_type WHEN 'D' THEN 'Full DB Restore'
WHEN 'F' THEN 'File Restore'
WHEN 'G' THEN 'Filegroup Restore'
WHEN 'I' THEN 'Differential Restore'
WHEN 'L' THEN 'Log Restore'
WHEN 'V' THEN 'Verify Only'
END,
ServerWhereBackupTaken = BS.server_name,
UserWhoBackedUpTheDatabase = BS.user_name,
BackupOfDatabase = BS.database_name,
DateOfBackup = BS.backup_start_date,
RestoredFromPath = BMF.physical_device_name
FROM
msdb.dbo.restorehistory RH
INNER JOIN
msdb.dbo.backupset BS
ON
RH.backup_set_id = BS.backup_set_id
INNER JOIN
msdb.dbo.backupmediafamily BMF
ON
BS.media_set_id = BMF.media_set_id
ORDER BY
RH.restore_history_id
/*
You might have seen a number of queries which provides you with top 10 or top 5
worst performing queries either by Logical IO’s or by CPU time or by Elapsed Time..
I have similar query but it does many more thing.
I personally do not query either by total logical reads or total cpu time or total
elapsed time individually. I usually use this query to get the queries which are
top n on a number of counters like say top 5 by ‘Total Logical Reads’ and top 5 by
‘Total CPU Time’ and top 5 by ‘Total Elapsed Time’ etc. Thus I will be able to find
the queries which are performing bad not just on one counter but on a number of
counters. Thus I will be able to find “true” worst perforaming query. I used word
“true” because sometime a query using more CPU time as it is a parallel query
whereas it is not taking too much time to actuall execute query (or the total
elapsed time rank is not say even in top 20). However, there is something which is
still missing. There are queries which are using the memory grant for sort and hash
joins. This value is not included here.However, for such queries CPU time is more
and thus these kind of queries might come up in top queries by CPU time.
*/
with PerformanceMetrics
as
(
select
--dest.text,
--statement_start_offset,
--statement_end_offset,
--LEN(dest.text) ln,
substring
(
dest.text,
statement_start_offset/2,
case when statement_end_offset = -1 then LEN(dest.text)
else statement_end_offset
end /2
) as 'Text of the SQL' ,
deqs.plan_generation_num as 'Number of times the plan was generated for this SQL',
execution_count as 'Total Number of Times the SQL was executed',
DENSE_RANK() over(order by execution_count desc) as 'Rank of the SQL by Total
number of Executions',
total_elapsed_time/1000 as 'Total Elapsed Time in ms consumed by this SQL',
DENSE_RANK() over(order by total_elapsed_time desc) as 'Rank of the SQL by Total
Elapsed Time',
Max_elapsed_time/1000 as 'Maximum Elapsed Time in ms consumed by this SQL',
min_elapsed_time/1000 as 'Minimum Elapsed Time in ms consumed by this SQL',
total_elapsed_time/1000*nullif(execution_count,0) as 'Average Elapsed Time in ms
consumed by this SQL',
DENSE_RANK() over(order by total_elapsed_time/nullif(execution_count,0) desc) as
'Rank of the SQL by Average Elapsed Time',
total_worker_time as 'Total CPU Time in ms consumed by this SQL',
DENSE_RANK() over(order by total_worker_time desc) as 'Rank of the SQL by Total CPU
Time',
Max_worker_time as 'Maximum CPU Time in ms consumed by this SQL',
min_worker_time as 'Minimum CPU Time in ms consumed by this SQL',
total_worker_time/nullif(execution_count,0) as 'Average CPU Time in ms consumed by
this SQL',
DENSE_RANK() over(order by total_worker_time/nullif(execution_count,0) desc) as
'Rank of the SQL by Average CPU Time',
total_logical_reads as 'Total Logical Reads Clocked by this SQL',
DENSE_RANK() over(order by total_logical_reads desc) as 'Rank of the SQL by Total
Logical reads',
Max_logical_reads as 'Maximum Logical Reads Clocked by this SQL',
min_logical_reads as 'Minimum Logical Reads Clocked by this SQL',
total_logical_reads/nullif(execution_count,0) as 'Average Logical Reads Clocked by
this SQL',
DENSE_RANK() over(order by total_logical_reads/nullif(execution_count,0) desc) as
'Rank of the SQL by Average Logical reads',
total_physical_reads as 'Total Physical Reads Clocked by this SQL',
DENSE_RANK() over(order by total_physical_reads desc) as 'Rank of the SQL by Total
Physical Reads',
Max_physical_reads as 'Maximum Physical Reads Clocked by this SQL',
min_physical_reads as 'Minimum Physical Reads Clocked by this SQL',
total_physical_reads/nullif(execution_count,0) as 'Average Physical Reads Clocked
by this SQL',
DENSE_RANK() over(order by total_physical_reads/nullif(execution_count,0) desc) as
'Rank of the SQL by Average Physical Reads',
total_logical_writes as 'Total Logical Writes Clocked by this SQL',
DENSE_RANK() over(order by total_logical_writes desc) as 'Rank of the SQL by Total
Logical Writes',
Max_logical_writes as 'Maximum Logical Writes Clocked by this SQL',
min_logical_writes as 'Minimum Logical Writes Clocked by this SQL',
total_logical_writes/nullif(execution_count,0) as 'Average Logical Writes Clocked
by this SQL',
DENSE_RANK() over(order by total_logical_writes/nullif(execution_count,0) desc) as
'Rank of the SQL by Average Logical Writes',
deqp.query_plan as 'Plan of Query'
--similarly you can add the ranks for maximum values as well.That is quite useful
in finding some of the perf issues.
from
sys.dm_exec_query_stats deqs
/*F0C6560A-9AD1-448B-9521-05258EF7E3FA*/ --use a newid so that we could exclude
this query from the performanc emetrics output
outer apply sys.dm_exec_query_plan(deqs.plan_handle) deqp --sometimes the plan
might not be in the cache any longer.So using outer apply
outer apply sys.dm_exec_sql_text(deqs.sql_handle) dest --Sometimes the text is not
returned by the dmv so use outer apply.
where
dest.text not like '%F0C6560A-9AD1-448B-9521-05258EF7E3FA%'
)
select
*
from
PerformanceMetrics
where
1=1
--apply any of these where clause in any combinations or one by one..
--and [Rank of the SQL by Average CPU Time] <= 20 --Use this to find the top N
queries by avg CPU time.
--and [Rank of the SQL by Average Elapsed Time] <= 20 --Use this to find the top N
queries by avg elspsed time.
--and [Rank of the SQL by Average Logical reads] <= 20 --Use this to find the top N
queries by avg logical reads.
--and [Rank of the SQL by Average Physical Reads] <= 20 --Use this to find the top
N queries by avg physical reads.
and [Rank of the SQL by Total CPU Time] <= 20 --Use this to find the top N queries
by total CPU time.
and [Rank of the SQL by Total Elapsed Time] <= 20 --Use this to find the top N
queries by total elapsed time.
and [Rank of the SQL by Total Logical reads] <= 20 --Use this to find the top N
queries by Total Logical reads.
and [Rank of the SQL by Total Physical Reads] <= 20 --Use this to find the top N
queries by Total Physical Reads.
and [Rank of the SQL by Total number of Executions] <= 20 --Use this to find the
top N queries by Total number of Executions.
--and [Rank of the SQL by Average Logical Writes] <= 20 --Use this to find the top
N queries by Average Logical Writes.
and [Rank of the SQL by Total Logical Writes] <= 20 --Use this to find the top N
queries by Total Logical Writes.
--I usually do the query by 6 rank types together Total logical reads,Total CPU
time, Total Elapsed Time , Total Execution count ,Total Physical Reads and Total
Logical Writes.Sometimes I exclude last two counters if i do not get any query in
the output.
--If some queries are say in top 10 in all these 6 categories then these needs to
tune first...
--But sometime you might not get any rows at all if u use these 6 categiories in
that case remove one of these categories or try one by one..
Task Progress:
--------------
--This is quite helpful to check the backup progress, restore progress, integrity
check progress, rebuild index task progress etc.
select
convert (varchar(50),(estimated_completion_time/3600000))+'hrs'+
convert (varchar(50), ((estimated_completion_time%3600000)/60000))+'min'+
convert (varchar(50), (((estimated_completion_time%3600000)%60000)/1000))+'sec'
as Estimated_Completion_Time,
status, command, db_name(database_id), percent_complete
from sys.dm_exec_requests
/*
Build Job Parent/Child Hierarchy using the Parent Job Name
Author: Ray Sotkiewicz, March 2011
Email: raysot @ comcast DOT Net
Use freely.
*/
--------------------------------------------------------------
--------------------------------------------------------------
------------------------------------------
-- Create work Table
------------------------------------------
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#JobWork') IS NOT NULL
BEGIN
Drop Table #JobWork
????Create table #JobWork
????(
???????? Parent_Job_Name SYSNAME
????????,Job_Name SYSNAME
????????,Step_ID INT
????????,Step_Name SYSNAME
????????,Child_Job_Name SYSNAME
????????,Processed BIT
????)????
END
------------------------------------------
-- Insert Top-Level (Parent) Job Name
------------------------------------------
--INSERT #JobWork( Job_Name, Step_ID, Step_Name, Child_Job_Name, Processed) VALUES
(@JobNAme, 0, '', '', 1)
------------------------------------------
-- Get Child Jobs: (Children)
------------------------------------------
INSERT #JobWork
Select???? @JobName AS 'Parent_Job_Name'
????????,sj.[name] AS 'Job_Name'
????????,sjs.Step_ID
????????,sjs.step_name
????????,substring(Command, (29), (Len(Command)-29 ) ) AS 'Child_Job_Name'
????????,0 as 'Processed'????????
from msdb..sysjobs sj
INNER JOIN msdb..sysjobsteps sjs on sj.job_id = sjs.job_ID
Where sj.name = @JobName
AND sjs.command LIKE 'EXEC msdb.dbo.sp_start_job%'
AND sjs.subsystem = 'TSQL'
---------------------------------
-- Interim Validation
---------------------------------
--Select * from #JobWork
---------------------------------
-- Loop to find more child jobs
---------------------------------
StartLoop:
OPEN JOB_cursor
FETCH NEXT FROM JOB_cursor INTO @_JOBName
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT #JobWork
????????????????,sjs.Step_ID
????????????????,sjs.step_name
????????????????,0 as 'Processed'????????
????????from msdb..sysjobs sj
????????
????????Update #JobWork Set Processed = 1 where Child_Job_Name = @_JobName
END
CLOSE JOB_cursor
DEALLOCATE JOB_cursor
----------------------------------------
----------------------------------------
BEGIN
????Goto StartLoop
END
---------------------------------
-- Interim Validation
---------------------------------
-------------------------------------------------------
-------------------------------------------------------
????Select????-- sj.job_id
????????????,sjs.Step_ID
????????????,sjs.Command
????from msdb..sysjobs sj
-------------------------------------------------------
-------------------------------------------------------
OPEN Step_cursor
WHILE @@FETCH_STATUS = 0
BEGIN
????Select????-- sj.job_id
????????????,sjs.Step_ID
????????????,sjs.Command
????from msdb..sysjobs sj
????INNER JOIN msdb..sysjobsteps sjs ON sj.job_id = sjs.job_id
????????
END
CLOSE STEP_cursor
DEALLOCATE STEP_cursor
)
as
if @sql = '' or @fullFileName = ''
begin
select 0 as ReturnValue -- failure
return
end
-- if DB isn't passed in set it to master
select @dbName = 'use ' + @dbName + ';'
if object_id('##TempExportData') is not null
drop table ##TempExportData
if object_id('##TempExportData2') is not null
drop table ##TempExportData2
-- insert data into a global temp table
declare @columnNames varchar(8000), @columnConvert varchar(8000), @tempSQL
varchar(8000)
exec(@dbName + @tempSQL)
if @@error > 0
begin
select 0 as ReturnValue -- failure
return
end
-- build 2 lists
-- 1. column names
-- 2. columns converted to nvarchar
SELECT @columnNames = COALESCE( @columnNames + ',', '') + column_name,
@columnConvert = COALESCE( @columnConvert + ',', '') + 'convert(nvarchar(4000),'
+ column_name + case when data_type in ('datetime', 'smalldatetime') then ',121'
when data_type in ('numeric', 'decimal') then ',128'
when data_type in ('float', 'real', 'money', 'smallmoney') then ',2'
when data_type in ('datetime', 'smalldatetime') then ',120'
else ''
end + ') as ' + column_name
FROM tempdb.INFORMATION_SCHEMA.Columns
WHERE table_name = '##TempExportData'
-- execute select query to insert data and column names into new temp table
SELECT @sql = 'select ' + @columnNames + ' into ##TempExportData2 from (select ' +
@columnConvert + ', ''2'' as [temp##SortID] from ##TempExportData union all select
''' + replace(@columnNames, ',', ''', ''') + ''', ''1'') t order by [temp##SortID]'
exec (@sql)
-- build full BCP query
DECLARE @bcpCommand VARCHAR(8000)
SET @bcpCommand = 'bcp " SELECT * from ##TempExportData2" queryout'
SET @bcpCommand = @bcpCommand + ' C:\Temp\test.csv -c -w -T -U sa -P sa","-CRAW'
EXEC <database>..xp_cmdshell @bcpCommand
if @@error > 0
begin
select 0 as ReturnValue -- failure
return
end
drop table ##TempExportData
drop table ##TempExportData2
set @columnNames =' '
set @columnConvert =' '
set @tempSQL =' '
select 1 as ReturnValue
/*
--
***********************************************************************************
*
-- Description:????This script list the current locking block chain.
--????????????It will create 1 function: fn_GetLockChainSubTree
--???????????????????? 1 table: LockChain
--
--
-- Parameters: NONE
--
-- Returns: Locking block chain
--
-- Created:???? 9/07/2008????John Liu
--
-- Typical Usage:????This script is typically used to find the block chain
information
--
-- Comments: It also lists the dead lock (if any) at the end.
--??????This script is for SQL 2005 and SQL 2008
--
--
-- Modifications:
--
-- Initials Date Description
-- -------- ---------- -----------------------------------------------------------
--
--
***********************************************************************************
*
*/
UNION all
INSERT INTO
@TREE
SELECT
*
FROM
Block_Subtree
RETURN
END
GO
--***************************************** End of dbo.fn_GetLockChainSubTree
************************
--***************************************End of create functions
********************************
--
***********************************************************************************
**
--**********************************???????? Main section ????????
**************************
--
***********************************************************************************
**
-- -----------------------------------------------
-- Core processing
-- -----------------------------------------------
IF OBJECT_ID('LockChain') IS NOT NULL DROP TABLE LockChain
go
-- -----------------------------------------------
-- End of Core processing
-- -----------------------------------------------
--***************************************** End of Main section
**********************************
/* Q2
What User has been running a fair few reports today?
-------------------------------------------------------
*/
SELECT UserName
,COUNT(*) AS FullSum
FROM dbo.ExecutionLog AS A WITH(NOLOCK)
INNER JOIN dbo.Catalog AS C WITH(NOLOCK)
ON A.ReportID = C.ItemID
WHERE CAST(TimeStart AS DATE) = CAST(GETDATE() AS DATE)
GROUP BY
UserName
ORDER BY 2 DESC
/* Q3
What report has been executed the most today?
*/
SELECT C.Path+'/'+C.Name AS Path
,COUNT(*) AS FullSum
FROM dbo.ExecutionLog AS A WITH(NOLOCK)
INNER JOIN dbo.Catalog AS C WITH(NOLOCK)
ON A.ReportID = C.ItemID
WHERE CAST(TimeStart AS DATE) = CAST(GETDATE() AS DATE)
GROUP BY
C.Path+'/'+C.Name
ORDER BY 2 DESC
select
[PagelockObject] = @deadlock.value('/deadlock-list[1]/deadlock[1]/resource-
list[1]/pagelock[1]/@objectname', 'varchar(200)'),
[DeadlockObject] = @deadlock.value('/deadlock-list[1]/deadlock[1]/resource-
list[1]/objectlock[1]/@objectname', 'varchar(200)'),
[KeylockObject] = Keylock.Process.value('@objectname', 'varchar(200)'),
[Index] = Keylock.Process.value('@indexname', 'varchar(200)'),
[IndexLockMode] = Keylock.Process.value('@mode', 'varchar(5)'),
[Victim] = case when Deadlock.Process.value('@id', 'varchar(50)') =
@deadlock.value('/deadlock-list[1]/deadlock[1]/@victim', 'varchar(50)') then 1 else
0 end,
[Procedure] = Deadlock.Process.value('executionStack[1]/frame[1]/@procname[1]',
'varchar(200)'),
[LockMode] = Deadlock.Process.value('@lockMode', 'char(1)'),
[Code] = Deadlock.Process.value('executionStack[1]/frame[1]', 'varchar(1000)'),
[ClientApp] = Deadlock.Process.value('@clientapp', 'varchar(100)'),
[HostName] = Deadlock.Process.value('@hostname', 'varchar(20)'),
[LoginName] = Deadlock.Process.value('@loginname', 'varchar(20)'),
[TransactionTime] = Deadlock.Process.value('@lasttranstarted', 'datetime'),
[InputBuffer] = Deadlock.Process.value('inputbuf[1]', 'varchar(1000)')
from @deadlock.nodes('/deadlock-list/deadlock/process-list/process') as
Deadlock(Process)
LEFT JOIN @deadlock.nodes('/deadlock-list/deadlock/resource-list/keylock') as
Keylock(Process)
ON Keylock.Process.value('owner-list[1]/owner[1]/@id', 'varchar(50)') =
Deadlock.Process.value('@id', 'varchar(50)')
Database Growth:
-------------------
GO
/****** Object: StoredProcedure [dbo].[sp_track_db_growth] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[sp_track_db_growth]
(
@dbnameParam sysname = NULL
)
AS
BEGIN
) as Derived
WHERE (Growth <> 0.0) OR (Growth IS NULL)
ORDER BY logical_name, [Date]
END
Growth History:
-----------------
;WITH HIST AS
(SELECT BS.database_name AS DatabaseName
,YEAR(BS.backup_start_date) * 100
+ MONTH(BS.backup_start_date) AS YearMonth
,CONVERT(numeric(10, 1), MIN(BF.file_size / 1048576.0)) AS MinSizeMB
,CONVERT(numeric(10, 1), MAX(BF.file_size / 1048576.0)) AS MaxSizeMB
,CONVERT(numeric(10, 1), AVG(BF.file_size / 1048576.0)) AS AvgSizeMB
FROM msdb.dbo.backupset as BS
INNER JOIN
msdb.dbo.backupfile AS BF
ON BS.backup_set_id = BF.backup_set_id
WHERE NOT BS.database_name IN
('master', 'msdb', 'model', 'tempdb')
AND BF.file_type = 'D'
AND BS.backup_start_date BETWEEN DATEADD(mm, - @months, @endDate) AND
@endDate
GROUP BY BS.database_name
,YEAR(BS.backup_start_date)
,MONTH(BS.backup_start_date))
SELECT MAIN.DatabaseName
,MAIN.YearMonth
,MAIN.MinSizeMB
,MAIN.MaxSizeMB
,MAIN.AvgSizeMB
,MAIN.AvgSizeMB
- (SELECT TOP 1 SUB.AvgSizeMB
FROM HIST AS SUB
WHERE SUB.DatabaseName = MAIN.DatabaseName
AND SUB.YearMonth < MAIN.YearMonth
ORDER BY SUB.YearMonth DESC) AS GrowthMB
FROM HIST AS MAIN
ORDER BY MAIN.DatabaseName
,MAIN.YearMonth
Script to check the database users and their roles:
--------------------------------------------------
SELECT
(physical_memory_in_use_kb/1024) AS Memory_usedby_Sqlserver_MB,
(locked_page_allocations_kb/1024) AS Locked_pages_used_Sqlserver_MB,
(total_virtual_address_space_kb/1024) AS Total_VAS_in_MB,
process_physical_memory_low,
process_virtual_memory_low
FROM sys.dm_os_process_memory;
last backup:
----------
SELECT
DISTINCT
a.Name AS DatabaseName ,
CONVERT(SYSNAME, DATABASEPROPERTYEX(a.name, 'Recovery')) RecoveryModel ,
COALESCE(( SELECT CONVERT(VARCHAR(12), MAX(backup_finish_date), 101)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'd'
AND is_copy_only = '0'
), 'No Full') AS 'Full' ,
COALESCE(( SELECT CONVERT(VARCHAR(12), MAX(backup_finish_date), 101)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'i'
AND is_copy_only = '0'
), 'No Diff') AS 'Diff' ,
COALESCE(( SELECT CONVERT(VARCHAR(20), MAX(backup_finish_date), 120)
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'l'
), 'No Log') AS 'LastLog' ,
COALESCE(( SELECT CONVERT(VARCHAR(20), backup_finish_date, 120)
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY
backup_finish_date DESC ) AS 'rownum' ,
backup_finish_date
FROM msdb.dbo.backupset
WHERE database_name = a.name
AND type = 'l'
) withrownum
WHERE rownum = 2
), 'No Log') AS 'LastLog2'
FROM sys.databases a
LEFT OUTER JOIN msdb.dbo.backupset b ON b.database_name = a.name
WHERE a.name <> 'tempdb'
AND a.state_desc = 'online'
GROUP BY a.Name ,
a.compatibility_level
ORDER BY a.name
Taking backup:
---------------
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName with compression
CLOSE db_cursor
DEALLOCATE db_cursor
script to identify the space used in each file and the top tables that have highest
number of rows :
-----------------------------------------------------------------------------------
------------------
SELECT
ds.name as filegroupname
, df.name AS 'FileName'
, physical_name AS 'PhysicalName'
, size/128 AS 'TotalSizeinMB'
, size/128.0 - CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS
'AvailableSpaceInMB'
, CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS 'ActualSpaceUsedInMB'
, (CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0)/(size/128)*100. as
'%SpaceUsed'
FROM sys.database_files df LEFT OUTER JOIN sys.data_spaces ds
ON df.data_space_id = ds.data_space_id;
EXEC xp_fixeddrives
select t.name as TableName,
i.name as IndexName,
p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
on fg.data_space_id = df.data_space_id join sys.indexes i (nolock)
on df.data_space_id = i.data_space_id join sys.tables t (nolock)
on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id
where fg.name = 'PRIMARY' and t.type = 'U'
order by rows desc
select t.name as TableName,
i.name as IndexName,
p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
on fg.data_space_id = df.data_space_id join sys.indexes i (nolock)
on df.data_space_id = i.data_space_id join sys.tables t (nolock)
on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id
where fg.name = 'PRIMARY' and t.type = 'U' and i.index_id = 0
order by rows desc