SQL常用性能相关脚本

--查询当前的事务

select
t2.session_id as SPID,
t2.transaction_id,
transaction_begin_time,
N‘已执行‘+ltrim(datediff(mi,transaction_begin_time,getdate()))+N‘分钟‘ as mi,
case transaction_type
when 1 then N‘读/写事务‘
when 2 then N‘只读事务‘
when 3 then N‘系统事务‘
when 4 then N‘分布式事务‘ end tran_Type,
case transaction_state
when 0 then N‘事务尚未完全初始化‘
when 1 then N‘事务已初始化但尚未启动‘
when 2 then N‘事务处于活动状态‘
when 3 then N‘事务已结束。该状态用于只读事务‘
when 4 then N‘已对分布式事务启动提交进程‘
when 5 then N‘事务处于准备就绪状态且等待解析‘
when 6 then N‘事务已提交‘
when 7 then N‘事务正在被回滚‘
when 0 then N‘事务已回滚‘
end transaction_state,
client_net_address,
client_tcp_port,
program_name,
t2.text

from
sys.dm_tran_active_transactions t1 join (
select
a.session_id,
transaction_id,
client_net_address,
client_tcp_port,
text,c.program_name
from sys.dm_tran_session_transactions a join (
select session_id,a2.text,client_net_address,client_tcp_port from sys.dm_exec_connections a1
cross apply sys.dm_exec_sql_text(a1.most_recent_sql_Handle) a2
) b on a.session_id=b.session_id
left join sys.dm_exec_sessions c on a.session_id=c.session_id
where is_user_transaction=1
)t2 on t1.transaction_ID=t2.transaction_ID
ORDER BY t2.transaction_id

----索引执行情况
SELECT objects.name ,
databases.name ,
indexes.name ,
user_seeks ,
user_scans ,
user_lookups ,
partition_stats.row_count
FROM sys.dm_db_index_usage_stats stats
LEFT JOIN sys.objects objects ON stats.object_id = objects.object_id
LEFT JOIN sys.databases databases ON databases.database_id = stats.database_id
LEFT JOIN sys.indexes indexes ON indexes.index_id = stats.index_id
AND stats.object_id = indexes.object_id
LEFT JOIN sys.dm_db_partition_stats partition_stats ON stats.object_id = partition_stats.object_id
AND indexes.index_id = partition_stats.index_id
WHERE 1 = 1
--AND databases.database_id = 7
AND objects.name IS NOT NULL
AND indexes.name IS NOT NULL
AND user_scans>0
ORDER BY user_scans DESC ,stats.object_id ,indexes.index_id

----最占用CPU
SELECT TOP 100 execution_count,
total_logical_reads /execution_count AS [Avg Logical Reads],
total_elapsed_time /execution_count AS [Avg Elapsed Time],
db_name(st.dbid) as [database name],
object_name(st.dbid) as [object name],
object_name(st.objectid) as [object name 1],
SUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,
((CASE statement_end_offset WHEN - 1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset)
/ 2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE execution_count > 100 AND qs.creation_time > dateadd(day,-3,getdate())
ORDER BY 1 DESC;

---执行时间最长的命令

SELECT TOP 10 COALESCE(DB_NAME(st.dbid),
DB_NAME(CAST(pa.value as int))+‘*‘,‘Resource‘) AS DBNAME,
SUBSTRING(text,
-- starting value for substring
CASE WHEN statement_start_offset = 0
OR statement_start_offset IS NULL
THEN 1
ELSE statement_start_offset/2 + 1 END,
-- ending value for substring
CASE WHEN statement_end_offset = 0
OR statement_end_offset = -1
OR statement_end_offset IS NULL
THEN LEN(text)
ELSE statement_end_offset/2 END -
CASE WHEN statement_start_offset = 0
OR statement_start_offset IS NULL
THEN 1
ELSE statement_start_offset/2 END + 1
) AS TSQL,
total_logical_reads/execution_count AS AVG_LOGICAL_READS
FROM sys.dm_exec_query_stats
CROSS APPLY sys.dm_exec_sql_text(sql_handle) st
OUTER APPLY sys.dm_exec_plan_attributes(plan_handle) pa
WHERE attribute = ‘dbid‘
ORDER BY AVG_LOGICAL_READS DESC ;

----缺索引

SELECT TOP 30
[Total Cost] = ROUND(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0)
, avg_user_impact, TableName = statement, [EqualityUsage] = equality_columns
, [InequalityUsage] = inequality_columns, [Include Cloumns] = included_columns
FROM sys.dm_db_missing_index_groups g
INNER JOIN sys.dm_db_missing_index_group_stats s
ON s.group_handle = g.index_group_handle
INNER JOIN sys.dm_db_missing_index_details d
ON d.index_handle = g.index_handle
ORDER BY [Total Cost] DESC;

--经常更新却很少使用的索引
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
DB_NAME() AS DatabaseName
, SCHEMA_NAME(o.Schema_ID) AS SchemaName
, OBJECT_NAME(s.[object_id]) AS TableName
, i.name AS IndexName
, s.user_updates
, s.system_seeks + s.system_scans + s.system_lookups
AS [System usage]
INTO #TempUnusedIndexes
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
AND s.index_id = i.index_id
INNER JOIN sys.objects o ON i.object_id = O.object_id
WHERE 1=2
EXEC sp_MSForEachDB ‘USE [?];
INSERT INTO #TempUnusedIndexes
SELECT TOP 20
DB_NAME() AS DatabaseName
, SCHEMA_NAME(o.Schema_ID) AS SchemaName
, OBJECT_NAME(s.[object_id]) AS TableName
, i.name AS IndexName
, s.user_updates
, s.system_seeks + s.system_scans + s.system_lookups
AS [System usage]
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
AND s.index_id = i.index_id
INNER JOIN sys.objects o ON i.object_id = O.object_id
WHERE s.database_id = DB_ID()
AND OBJECTPROPERTY(s.[object_id], ‘‘IsMsShipped‘‘) = 0
AND s.user_seeks = 0
AND s.user_scans = 0
AND s.user_lookups = 0
AND i.name IS NOT NULL
ORDER BY s.user_updates DESC‘
SELECT TOP 20 * FROM #TempUnusedIndexes
WHERE DatabaseName = ‘agilepoint50‘ ORDER BY [user_updates] DESC
DROP TABLE #TempUnusedIndexes

---维护代价最高的索引
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
DB_NAME() AS DatabaseName
, SCHEMA_NAME(o.Schema_ID) AS SchemaName
, OBJECT_NAME(s.[object_id]) AS TableName
, i.name AS IndexName
, (s.user_updates ) AS [update usage]
, (s.user_seeks + s.user_scans + s.user_lookups) AS [Retrieval usage]
, (s.user_updates) -
(s.user_seeks + s.user_scans + s.user_lookups) AS [Maintenance cost]
, s.system_seeks + s.system_scans + s.system_lookups AS [System usage]
, s.last_user_seek
, s.last_user_scan
, s.last_user_lookup
INTO #TempMaintenanceCost
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
AND s.index_id = i.index_id
INNER JOIN sys.objects o ON i.object_id = O.object_id
WHERE 1=2
EXEC sp_MSForEachDB ‘USE [?];
INSERT INTO #TempMaintenanceCost
SELECT TOP 20
DB_NAME() AS DatabaseName
, SCHEMA_NAME(o.Schema_ID) AS SchemaName
, OBJECT_NAME(s.[object_id]) AS TableName
, i.name AS IndexName
, (s.user_updates ) AS [update usage]
, (s.user_seeks + s.user_scans + s.user_lookups)
AS [Retrieval usage]
, (s.user_updates) -
(s.user_seeks + user_scans +
s.user_lookups) AS [Maintenance cost]
, s.system_seeks + s.system_scans + s.system_lookups AS [System usage]
, s.last_user_seek
, s.last_user_scan
, s.last_user_lookup
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id]
AND s.index_id = i.index_id
INNER JOIN sys.objects o ON i.object_id = O.object_id
WHERE s.database_id = DB_ID()
AND i.name IS NOT NULL
AND OBJECTPROPERTY(s.[object_id], ‘‘IsMsShipped‘‘) = 0
AND (s.user_seeks + s.user_scans + s.user_lookups) > 0
ORDER BY [Maintenance cost] DESC‘
SELECT top 20 * FROM #TempMaintenanceCost WHERE DatabaseName =‘agilepoint50‘ ORDER BY [Maintenance cost] DESC
DROP TABLE #TempMaintenanceCost

---表及数据库的空间占用
set nocount on
declare @db varchar(20)
set @db = db_name()
dbcc updateusage(@db) with no_infomsgs
go

create table #tblspace
(

数据表名称 varchar(50) null,
记录笔数 int null,
保留空间 varchar(15) null,
数据使用空间 varchar(15) null,
索引使用空间 varchar(15) null,
未使用空间 varchar(15) null,

)
declare @tblname varchar(50)
declare curtbls cursor for
select table_name from information_schema.tables
where table_type = ‘base table‘
open curtbls
Fetch next from curtbls into @tblname
while @@fetch_status = 0
begin
insert #tblspace exec sp_spaceused @tblname
fetch next from curtbls into @tblname
end
close curtbls
deallocate curtbls

select * from #tblspace order by
convert(int,left(保留空间,len(保留空间)-2)) desc
drop table #tblspace
时间: 2024-10-10 22:58:12

SQL常用性能相关脚本的相关文章

SQL常用性能统计语句

1.查看SQL语句IO消耗 set statistics io on     sql 语句 set statistics io off 2.查看SQL语句时间消耗 set statistics time on      sql 语句set statistics time off 3.查看SQL语句索引消耗 set statistics profile on        sql 语句 set statistics profile off

Oracle 性能相关常用脚本(SQL)

在缺乏的可视化工具来监控数据库性能的情形下,常用的脚本就派上用场了,下面提供几个关于Oracle性能相关的脚本供大家参考.以下脚本均在Oracle 10g测试通过,Oracle 11g可能要做相应调整. 1.寻找最多BUFFER_GETS开销的SQL 语句 [sql] view plain copy print? --filename: top_sql_by_buffer_gets.sql --Identify heavy SQL (Get the SQL with heavy BUFFER_G

SQL Server性能常用语句

查看各表的数据行数 SELECT o.name, i. ROWS FROM sysobjects o, sysindexes i WHERE o.id = i.id AND o.Xtype = 'U' AND i.indid < 2 ORDER BY o.name; 计算数据库中各个表每行记录所占用空间 --SELECT * FROM Employees AS e; CREATE TABLE #tablespaceinfo ( nameinfo VARCHAR(50) , rowsinfo BI

SQL语句性能分析常用选项开关

DBCC freeproccache DBCC dropcleanbuffers 1.set statistics IO {ON| OFF} /*Transact-SQL 语句生成的磁盘活动量的信息*/2.set statistics time on {ON| OFF} /*显示分析.编译和执行各语句所需的毫秒数*/3.set statistics profile on 4.set showplan_all on {ON| OFF} /*返回有关语句执行情况的详细信息,并估计语句对资源的需求*/

ORACLE常用性能监控SQL【一】

目录(?)[+] 系列 ORACLE常用性能监控SQL[一] ORACLE常用性能监控SQL[二] Oracle-动态性能视图解读 系列 死锁后的解决办法 生成Kill Session语句 查看导致死锁的 SQL 查看谁锁了谁 ORA-00054 资源正忙要求指定 NOWAIT 查询绑定变量使用的实际值 监控事例的等待 回滚段的争用情况 查看回滚段名称及大小 查看控制文件 查看日志文件 查看前台正在发出的SQL语句 数据表占用空间大小情况 查看表空间碎片大小 查看表空间占用磁盘情况 查看表的大小

ORACLE常用性能监控SQL(二)

查询Oracle正在执行的sql语句及执行该语句的用户 SELECT b.sid oracleID, b.username 登录Oracle用户名, b.serial#, spid 操作系统ID, paddr, sql_text 正在执行的SQL, b.machine 计算机名 FROM v$process a, v$session b, v$sqlarea c WHERE a.addr = b.paddr AND b.sql_hash_value = c.hash_value 1 2 3 4

重新发现Oracle太美之awr相关脚本简单介绍

大家知道在$ORACLE_HOME/rdbms/admin下,有如下的相关脚本(我的环境为11.2.0.4.2): [[email protected] ~]$ cd $ORACLE_HOME/rdbms/admin [[email protected] admin]$ ls -ltr awr* -rw-r--r-- 1 oracle oinstall  1999 Oct 24  2003 awrrpt.sql -rw-r--r-- 1 oracle oinstall 49166 Sep  1

sql 常用语法汇总

Sql常用语法 SQL分类: DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT) DCL—数据控制语言(GRANT,REVOKE,COMMIT,ROLLBACK) 首先,简要介绍基础语句: 1.说明:创建数据库 CREATE DATABASE database-name 2.说明:删除数据库 drop database dbname 3.说明:备份sql server --- 创建 备份数据的

(转)SQL Server 性能调优(cpu)

摘自:http://www.cnblogs.com/Amaranthus/archive/2012/03/07/2383551.html 研究cpu压力工具 perfom SQL跟踪 性能视图 cpu相关的wait event Signal wait time SOS_SCHEDULER_YIELD等待 CXPACKET等待 CMEMTHREAD等待 调度队列 cpu密集型查询 高CPU使用率的创建几种状况 miss index 统计数据丢失 非SARG谓词 隐式类型转化 参数探测器 ad ho