转载自:https://www.cnblogs.com/vice/p/9163241.html
操作系统是windows2008r2 ,数据库是sql2014 64位。
近阶段服务器出现过几次死机,管理员反馈机器内存使用率100%导致机器卡死。于是做了个监测服务器的软件实时记录cpu数据,几日观察得出数据如下:
sql优化方法:
1、查看连接对象
1 use master 2 go 3 --如果要指定数据库就把注释去掉 4 select * from sys.[sysprocesses] where [spid]>50 --and db_name([dbid])='gposdb'
当前连接对象有67个其中‘winame’的主机名,‘jtds’的进程名不属于已知常用软件,找到这台主机并解决连接问题。在360流量防火墙中查看有哪个软件连接了服务器ip,除之。
2、然后使用下面语句看一下各项指标是否正常,是否有阻塞,正常情况下搜索结果应该为空。
按 ctrl+c 复制代码 按 ctrl+c 复制代码
查看是哪些sql语句占用较大可以使用下面代码
按 ctrl+c 复制代码 按 ctrl+c 复制代码
3、如果sqlserver存在要等待的资源,那么执行下面语句就会显示出会话中有多少个worker在等待
1 select top 10 2 [session_id], 3 [request_id], 4 [start_time] as '开始时间', 5 [status] as '状态', 6 [command] as '命令', 7 dest.[text] as 'sql语句', 8 db_name([database_id]) as '数据库名', 9 [blocking_session_id] as '正在阻塞其他会话的会话id', 10 der.[wait_type] as '等待资源类型', 11 [wait_time] as '等待时间', 12 [wait_resource] as '等待的资源', 13 [dows].[waiting_tasks_count] as '当前正在进行等待的任务数', 14 [reads] as '物理读次数', 15 [writes] as '写次数', 16 [logical_reads] as '逻辑读次数', 17 [row_count] as '返回结果行数' 18 from sys.[dm_exec_requests] as der 19 inner join [sys].[dm_os_wait_stats] as dows 20 on der.[wait_type]=[dows].[wait_type] 21 cross apply 22 sys.[dm_exec_sql_text](der.[sql_handle]) as dest 23 where [session_id]>50 24 order by [cpu_time] desc
4、查询cpu占用最高的sql语句
1 select top 10 2 total_worker_time/execution_count as avg_cpu_cost, plan_handle, 3 execution_count, 4 (select substring(text, statement_start_offset/2 + 1, 5 (case when statement_end_offset = -1 6 then len(convert(nvarchar(max), text)) * 2 7 else statement_end_offset 8 end - statement_start_offset)/2) 9 from sys.dm_exec_sql_text(sql_handle)) as query_text 10 from sys.dm_exec_query_stats 11 order by [avg_cpu_cost] desc
5、索引缺失查询
1 select 2 databasename = db_name(database_id) 3 ,[number indexes missing] = count(*) 4 from sys.dm_db_missing_index_details 5 group by db_name(database_id) 6 order by 2 desc; 7 select top 10 8 [total cost] = round(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0) 9 , avg_user_impact 10 , tablename = statement 11 , [equalityusage] = equality_columns 12 , [inequalityusage] = inequality_columns 13 , [include cloumns] = included_columns 14 from sys.dm_db_missing_index_groups g 15 inner join sys.dm_db_missing_index_group_stats s 16 on s.group_handle = g.index_group_handle 17 inner join sys.dm_db_missing_index_details d 18 on d.index_handle = g.index_handle 19 order by [total cost] desc;
找到索引缺失的表,根据查询结果中的关键次逐一建立索引。
做完这些测试,基本能找到问题。