小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

MS SQL 日常維護(hù)管理常用腳本(二)

 鷹皇軟件 2013-08-14

監(jiān)控數(shù)據(jù)庫運(yùn)行

下面是整理、收集監(jiān)控數(shù)據(jù)庫運(yùn)行的一些常用腳本,也是MS SQL 日常維護(hù)管理常用腳本(一)的續(xù)集,歡迎大家補(bǔ)充、提意見。

 

查看數(shù)據(jù)庫登錄名信息
 
Code Snippet
  1. SELECT name                                AS LoginName ,
  2.        dbname                              AS DefaultDB ,
  3.        createdate                          AS CreateDate,
  4.        updatedate                          AS UpdateDate,
  5.        language                            AS Language  ,
  6.        CASE WHEN isntname = 1 THEN 'NT USER'
  7.            ELSE 'SQL USER'    END          AS UserType
  8. FROM syslogins;

 

查看數(shù)據(jù)庫用戶信息
 
SELECT * FROM sysusers;
 
查看用戶擁有的服務(wù)器角色
 

方法1: 用SSMS管理工具查看


方法2: 腳本查詢

 
查看用戶角色
  1. SELECT name            ,
  2.        CASE WHEN sysadmin     = 1       THEN 'yes'     ELSE '' END AS IsSysadmin        ,
  3.        CASE WHEN dbcreator    = 1       THEN 'yes'     ELSE '' END AS IsDbCreate        ,
  4.        CASE WHEN securityadmin= 1       THEN 'yes'     ELSE '' END AS IsSecurityadmin   ,
  5.        CASE WHEN bulkadmin    = 1       THEN 'yes'     ELSE '' END AS IsBulkadmin       ,
  6.        CASE WHEN diskadmin    = 1       THEN 'yes'     ELSE '' END AS IsDiskadmin       ,
  7.        CASE WHEN processadmin = 1       THEN 'yes'     ELSE '' END AS IsProcessadmin    ,
  8.        CASE WHEN serveradmin  = 1       THEN 'yes'     ELSE '' END AS IsServeradmin     ,
  9.        CASE WHEN setupadmin   = 1       THEN 'yes'     ELSE '' END AS IsSetupadmin    
  10. FROM syslogins
  11. --WHERE NAME='loginname'
 
查看最大工作線程數(shù)
 
Code Snippet
  1. SELECT  max_workers_count
  2.   FROM  sys.dm_os_sys_info

 

查看當(dāng)前用戶進(jìn)程的會話ID

 

SELECT @@SPID

 

查詢當(dāng)前會話使用哪種協(xié)議

Code Snippet
  1. SELECT net_transport
  2. FROM   sys.dm_exec_connections
  3. WHERE session_id = @@SPID;
 
查看當(dāng)前連接的會話信息

--進(jìn)程號1--50是SQL Server系統(tǒng)內(nèi)部用的
SELECT * FROM sys.dm_exec_sessions WHERE session_id >=51
 
--查看某臺機(jī)器的連接會話信息
SELECT * FROM sys.dm_exec_sessions WHERE session_id >=51 AND host_name='PO130018801'
 
--查看某個登錄名的連接會話信息
SELECT * FROM sys.dm_exec_sessions WHERE session_id >=51 AND login_name='username'
 
--查看活動的連接會話信息
SELECT * FROM sys.dm_exec_sessions WITH(NOWAIT) WHERE session_id >=51 AND status ='running'
 
--查找連接到服務(wù)器的用戶并返回每個用戶的會話數(shù)
SELECT  login_name ,
        COUNT(session_id) AS session_count
FROM    sys.dm_exec_sessions
GROUP BY login_name ;
 
 
查看正在執(zhí)行的SQL語句
 

方法1: 選擇數(shù)據(jù)庫實(shí)例,單擊右鍵,選擇”活動監(jiān)視器“,監(jiān)控/查看正在執(zhí)行的SQL


方法2: profile去跟蹤,比較耗費(fèi)資源。

 

方法3:

 
Code Snippet
  1. SELECT[Spid] = session_Id ,
  2.       ecid ,
  3.       [Database] = DB_NAME(sp.dbid) ,
  4.       [User] = nt_username ,
  5.       [Status] = er.status ,
  6.       [Wait] = wait_type ,
  7.       [Individual Query] = SUBSTRING(qt.text, er.statement_start_offset / 2,
  8.                                      ( CASE WHEN er.statement_end_offset = -1
  9.                                             THEN LEN(CONVERT(NVARCHAR(MAX), qt.text))
  10.                                                  * 2
  11.                                             ELSE er.statement_end_offset
  12.                                        END - er.statement_start_offset ) / 2) ,
  13.       [Parent Query] = qt.text ,
  14.       Program = program_name ,
  15.       Hostname ,
  16.       nt_domain ,
  17.       start_time
  18.   FROMsys.dm_exec_requests er
  19.       INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
  20.       CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) AS qt
  21.  WHEREsession_Id >= 51

方法4:

Code Snippet
  1. SELECT   m.session_id ,
  2.          m.start_time ,
  3.          m.command    ,
  4.          m.wait_type  ,
  5.          m.cpu_time   ,
  6.         CAST(s.text AS VARCHAR(1000)) AS sqlText
  7.  FROMmaster.sys.dm_exec_requests m WITH ( NOLOCK )
  8.      CROSS APPLY fn_get_sql(m.sql_handle) s
  9.  
  10. SELECT  r.session_id,
  11.         r.start_time      ,
  12.         r.command         ,
  13.         r.wait_type       ,
  14.         r.cpu_time        ,
  15.         s.text  
  16.  FROMsys.dm_exec_requests r
  17.      CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s

--查看某個會話ID正在執(zhí)行的SQL

Code Snippet
  1. SELECT  m.session_id ,
  2.         m.start_time ,
  3.         m.command    ,
  4.         m.wait_type  ,
  5.         m.cpu_time   ,
  6.       CAST(s.text AS VARCHAR(1000)) AS sqlText
  7.   FROMmaster.sys.dm_exec_requests m WITH ( NOLOCK )
  8.       CROSS APPLY fn_get_sql(m.sql_handle) s
  9.  WHEREm.session_id = 342
  10.  
  11.     SELECT   r.session_id      ,
  12.              r.start_time      ,
  13.              r.command         ,
  14.              r.wait_type       ,
  15.              r.cpu_time        ,
  16.              s.text  
  17.   FROM sys.dm_exec_requests r
  18.       CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
  19. WHERE r.seesion_id =342

查看SQL SERVER進(jìn)程執(zhí)行的語句

Code Snippet
  1. USE master
  2.  
  3. DECLARE @spid INT ;
  4.  
  5. DECLARE @sql_handle BINARY(20) ;
  6.  
  7. SET @spid = 56
  8.  
  9.   SELECT@sql_handle = sql_handle
  10.     FROMsysprocesses AS A WITH ( NOLOCK )
  11.    WHEREspid = @spid ;
  12.  
  13.   SELECTtext
  14.     FROM::fn_get_sql(@sql_handle) ;
 
查找TOP N語句

按平均 CPU 時間返回排名前十個的查詢的相關(guān)信息。此示例將根據(jù)查詢的查詢哈希對查詢進(jìn)行聚合,以便按照查詢的累積資源消耗來分組在邏輯上等效的查詢。
--注意:SQL 2005 某些版本,沒有sys.dm_exec_query_stats系統(tǒng)動態(tài)視圖沒有query_hash視圖。

Code Snippet
  1. USE DBNAME;
  2. GO
  3. SELECT TOP 10 query_stats.query_hash             AS "Query Hash",
  4.     SUM(query_stats.total_worker_time) /
  5.     SUM(query_stats.execution_count)             AS "Avg CPU Time",
  6.     MIN(query_stats.statement_text)              AS "Statement Text"
  7. FROM
  8.     (SELECT QS.*,
  9.     SUBSTRING(ST.text,(QS.statement_start_offset/2) + 1,
  10.     ((CASE statement_end_offset
  11.         WHEN -1 THEN DATALENGTH(st.text)
  12.         ELSE QS.statement_end_offset END
  13.             - QS.statement_start_offset)/2) + 1) AS statement_text
  14.      FROM sys.dm_exec_query_stats AS QS
  15.      CROSS APPLY sys.dm_exec_sql_text(QS.sql_handle) as ST) as query_stats
  16. GROUP BY query_stats.query_hash
  17. ORDER BY 2 DESC;
  18. GO
查看會話阻塞/死鎖信息
 

方法1:查看那個引起阻塞,查看blk不為0的記錄,如果存在阻塞進(jìn)程,則是該阻塞進(jìn)程的會話 ID。否則該列為零。 

    EXEC sp_who active

方法2:查看那個引起阻塞,查看字段BlkBy,這個能夠得到比sp_who更多的信息。

    EXEC sp_who2 active

方法3:sp_lock 系統(tǒng)存儲過程,報告有關(guān)鎖的信息,但是不方便定位問題


方法4:sp_who_lock存儲過程

Code Snippet
  1. USE master;
  2. GO
  3.  
  4. SET ANSI_NULLS ON;
  5. GO
  6.  
  7. SET QUOTED_IDENTIFIER ON;
  8. GO
  9.  
  10. IF EXISTS(SELECT 1 FROM sysobjects WHERE id=OBJECT_ID(N'sp_who_lock')
  11.                                        AND OBJECTPROPERTY(id, 'IsProcedure') =1)
  12.     DROP PROCEDURE sp_who_lock;
  13. GO
  14.  
  15. --==================================================================================================
  16. --            ProcedureName             :            sp_who_lock
  17. --            Author                    :            作者不詳,出自網(wǎng)絡(luò)
  18. --            CreateDate                :            2013-05-13
  19. --            Description               :            查看阻塞和死鎖信息
  20. /**************************************************************************************************
  21.         Parameters                    :              參數(shù)說明
  22. ***************************************************************************************************
  23.                                                      無參存儲過程
  24. ***************************************************************************************************
  25.         Modified Date            Modified User     Version                 Modified Reason
  26. ***************************************************************************************************
  27.        2013-06-03                    Kerry        V01.00.01 調(diào)整存儲過程格式,代碼部分修改以及增加注釋信息
  28. ***************************************************************************************************/
  29. --=================================================================================================
  30.  
  31.   CREATE PROCEDURE sp_who_lock
  32.     AS
  33. BEGIN
  34.  
  35. DECLARE @spid                            INT;
  36. DECLARE @block                           INT;
  37. DECLARE @RowCount                        INT;
  38. DECLARE @RowIndex                        INT;
  39.  
  40. --創(chuàng)建臨時表,保持被阻塞或正阻塞其他SQL的SQL語句信息
  41. CREATE TABLE #tmp_lock_who
  42. (
  43.       id    INT IDENTITY(1, 1) ,
  44.       spid    SMALLINT ,
  45.       block SMALLINT
  46. )
  47.     
  48.     
  49. IF @@ERROR<>0 RETURN @@ERROR;
  50.  
  51. INSERT INTO #tmp_lock_who
  52.         (
  53.           spid ,
  54.           block
  55.         )
  56.         SELECT  0 ,
  57.                 blocked
  58.         FROM    ( SELECT    *
  59.                   FROM      sysprocesses
  60.                   WHERE     blocked > 0
  61.                 ) a
  62.         WHERE   NOT EXISTS( SELECT *
  63.                              FROM   ( SELECT    *
  64.                                       FROM      sysprocesses
  65.                                       WHERE     blocked > 0
  66.                                     ) b
  67.                              WHERE  a.blocked = spid )
  68.         UNION
  69.         SELECT  spid ,
  70.                 blocked
  71.         FROM    sysprocesses
  72.         WHERE   blocked > 0;
  73.         
  74.         
  75. IF @@ERROR<>0 RETURN @@ERROR;
  76.  
  77.  
  78. -- 找到臨時表的記錄數(shù)
  79.   SELECT@RowCount = COUNT(1) ,
  80.         @RowIndex = 1
  81.     FROM#tmp_lock_who
  82.  
  83.  
  84. IF @@ERROR<>0 RETURN @@ERROR;
  85.  
  86.   IF@RowCount=0
  87.   SELECT  N'現(xiàn)在沒有阻塞和死鎖信息' AS MESSAGE;
  88.  
  89.  
  90. -- -- 循環(huán)開始
  91. WHILE @RowIndex <= @RowCount
  92. BEGIN
  93.     -- 取第一條記錄
  94.     SELECT     @spid    = spid,
  95.                @block   = block
  96.     FROM #tmp_lock_who
  97.     WHERE Id = @RowIndex
  98.  
  99.     IF @spid = 0
  100.         SELECT N'引起數(shù)據(jù)庫死鎖的是: ' + CAST(@block AS VARCHAR(10))
  101.             +  N'進(jìn)程號,其執(zhí)行的SQL語法如下';
  102.     ELSE
  103.         SELECT N'進(jìn)程號SPID:' + CAST(@spid AS VARCHAR(10)) + N'被進(jìn)程號SPID:'
  104.             +  CAST(@block AS VARCHAR(10)) +'阻塞,其當(dāng)前進(jìn)程執(zhí)行的SQL語法如下';
  105.         
  106.     DBCC INPUTBUFFER(@block )
  107.  
  108.  
  109.     SET @RowIndex = @RowIndex + 1;
  110.  
  111. END;
  112.  
  113.     DROP TABLE #tmp_lock_who;
  114.  
  115.     RETURN 0;
  116. END

方法5:右鍵服務(wù)器-選擇“活動和監(jiān)視器”,查看進(jìn)程選項(xiàng)。注意“任務(wù)狀態(tài)”字段。

方法6:右鍵服務(wù)名稱-選擇報表-標(biāo)準(zhǔn)報表-活動-所有正在阻塞的事務(wù)。


小結(jié):總結(jié)之后,才發(fā)現(xiàn)居然有這么多方法,MGD,系統(tǒng)的整理、梳理知識點(diǎn)是非常有必要的,你能更全面、深入的了解。

 
查看內(nèi)存狀態(tài)

dbcc memorystatus


具體如何分析,請查看官方文檔http://support.microsoft.com/kb/907877/zh-cn

 
查看腳本執(zhí)行時間


方法1: 查看SSMS管理器,查詢窗口右下角
方法2:

Code Snippet
  1. DECLARE @exectime DATETIME
  2.   SELECT@exectime = GETDATE()
  3. --SQL 語句
  4. PRINT N'SQL執(zhí)行耗時:' + CONVERT(VARCHAR(10), DATEDIFF(ms, @exectime, GETDATE()))

方法3:

SET STATISTICS TIME ON

--SQL 語句

 

查看進(jìn)程正在執(zhí)行的SQL語句 

  dbcc inputbuffer ()

查看那些表缺少索引 

 

下面語句功能強(qiáng)大,執(zhí)行結(jié)果受統(tǒng)計信息的影響

Code Snippet
  1. SELECT sys.objects.name table_name,
  2.        mid.statement full_name,
  3.     (migs.avg_total_user_cost * migs.avg_user_impact) *(migs.user_seeks + migs.user_scans) AS Impact,
  4.     migs.avg_user_impact *(migs.user_seeks + migs.user_scans) Avg_Estimated_Impact,
  5.     'CREATE NONCLUSTERED INDEX IDX_' + sys.objects.name + '_N ON '
  6.         + sys.objects.name COLLATE DATABASE_DEFAULT
  7.         + ' ( ' + IsNull(mid.equality_columns, '')
  8.         + CASE WHEN mid.inequality_columns IS NULL
  9.                 THEN ''
  10.             ELSE
  11.                 CASE WHEN mid.equality_columns IS NULL
  12.                     THEN ''
  13.                 ELSE ','
  14.                 END + mid.inequality_columns
  15.             END + ' ) '
  16.         + CASE WHEN mid.included_columns IS NULL
  17.                 THEN ''
  18.             ELSE 'INCLUDE (' + mid.included_columns + ')' END
  19.         + ';' AS CreateIndexStatement,
  20.     mid.equality_columns,
  21.     mid.inequality_columns,
  22.     mid.included_columns
  23. FROM sys.dm_db_missing_index_group_stats AS migs
  24.     INNER JOIN sys.dm_db_missing_index_groups AS mig ON migs.group_handle = mig.index_group_handle
  25.     INNER JOIN sys.dm_db_missing_index_details AS mid ON mig.index_handle = mid.index_handle
  26.         AND mid.database_id = DB_ID()
  27.     INNER JOIN sys.objects WITH (nolock) ON mid.OBJECT_ID = sys.objects.OBJECT_ID
  28. WHERE (migs.group_handle IN
  29.         (
  30.             SELECT TOP (500) group_handle
  31.             FROM sys.dm_db_missing_index_group_stats WITH (nolock)
  32.             ORDER BY (avg_total_user_cost * avg_user_impact) *(user_seeks + user_scans) DESC))
  33.     AND OBJECTPROPERTY(sys.objects.OBJECT_ID, 'isusertable')=1
  34. --ORDER BY [Impact] DESC, [full_name] DESC
  35. ORDER BY [table_name], [Impact] desc

查看應(yīng)該被移除的索引

 

查看那些多余的、應(yīng)該被移除的索引

SQL 1:

Code Snippet
  1. SELECT OBJECTNAME = OBJECT_NAME(I.OBJECT_ID),
  2.     INDEXNAME = I.NAME,
  3.     I.INDEX_ID
  4. FROM SYS.INDEXES I
  5.     JOIN SYS.OBJECTS O ON I.OBJECT_ID = O.OBJECT_ID
  6. WHERE OBJECTPROPERTY(O.OBJECT_ID,'IsUserTable') = 1
  7.     AND I.INDEX_ID NOT IN(
  8.                             SELECT S.INDEX_ID
  9.                             FROM SYS.DM_DB_INDEX_USAGE_STATS S
  10.                             WHERE S.OBJECT_ID = I.OBJECT_ID
  11.                                 AND I.INDEX_ID = S.INDEX_ID
  12.                                 AND DATABASE_ID = DB_ID())
  13. ORDER BY OBJECTNAME, I.INDEX_ID, INDEXNAME ASC

SQL 2: 分析下面語句,移除那些沒有必要的索引

Code Snippet
  1. SELECT DB_NAME(database_id)         AS  N'DataBaseName'  ,
  2.        OBJECT_NAME(U.object_id)     AS  N'Table_Name'    ,
  3.        I.name                       AS  N'Index_Name'    ,
  4.        user_seeks                   AS  N'用戶索引查找次數(shù)',
  5.        user_scans                   AS  N'用戶索引掃描次數(shù)',
  6.        last_user_seek               AS  N'最后查找時間'   ,
  7.        last_user_scan               AS  N'最后掃描時間'   ,
  8.        rows                         AS  N'表中的行數(shù)'
  9. FROM sys.dm_db_index_usage_stats AS U
  10.    INNER JOIN sys.indexes I ON U.index_id= I.index_idAND U.object_id= I.object_id
  11.   INNER JOIN sysindexesT ON I.object_id = T.id
  12. WHERE database_id= DB_ID('DbName')
  13. AND OBJECT_NAME(U.object_id)='TableName'
  14. ORDER BY user_seeks, user_scans, object_name(U.object_id);
作者:瀟湘隱者

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多