如何用T-SQL語句來建立啟動跟蹤

來源:互聯網
上載者:User

 一般我們會用事件探查器來跟蹤SQL Server的運行情況,有時我們也需要定時進行一些跟蹤,以檢查SQL Server在某個時間段內的健全狀態,由於事件探查器不支援調度,因此,應該尋找一種方法,適合我們通過設定JOB來啟動跟蹤,本文介紹的用T-SQL語句來啟用跟蹤就適合這種需求。

  一、用指令碼啟動並設定跟蹤的樣本

  通過這個樣本,你可以瞭解用指令碼進行跟蹤所涉及到的預存程序,要瞭解這些預存程序的具體文法和參數的含義,請查詢線上說明


/****************************************************/ /* created by: SQL Profiler */ /* Date: 2004/06/19 16:50:05 */ /****************************************************/ -- create a Queue declare @rc int declare @TraceID int declare @maxfilesize bigint set @maxfilesize = 5 -- Please replace the text insertFileNameHere, with an appropriate -- filename prefixed by a path, e.g., c:/MyFolder/MyTrace. The .trc extension -- will be appended to the filename automatically. If you are writing from -- remote server to local drive, please use UNC path and make sure server has -- write access to your network share exec @rc = sp_trace_create @TraceID output, 0, N’c:/test’, @maxfilesize, NULL if (@rc != 0) goto error -- Client side File and Table cannot be scripted -- Writing to a table is not supported through the SP’s -- Set the events declare @on bit set @on = 1 exec sp_trace_setevent @TraceID, 12, 1, @on exec sp_trace_setevent @TraceID, 12, 12, @on exec sp_trace_setevent @TraceID, 12, 14, @on -- Set the Filters declare @intfilter int declare @bigintfilter bigint exec sp_trace_setfilter @TraceID, 10, 0, 7, N’SQL Profiler’ set @intfilter = 100 exec sp_trace_setfilter @TraceID, 22, 0, 4, @intfilter set @intfilter = 1 exec sp_trace_setfilter @TraceID, 23, 1, 0, @intfilter exec sp_trace_setfilter @TraceID, 35, 1, 6, N’pubs’ -- Set the trace status to start exec sp_trace_setstatus @TraceID, 1 -- display trace id for future references select TraceID=@TraceID goto finish error: select ErrorCode=@rc finish: go

 

  二、產生跟蹤指令碼的最簡式

  事件探查器建立跟蹤, 並設定好各種選項, 完成後運行跟蹤

  然後產生指令碼:

  事件探查器--檔案--匯出追蹤定義的檔案--選擇合適的版本.

  這樣就會產生一個跟蹤的指令碼, 開啟產生的指令碼, 修改裡面的:

  exec @rc = sp_trace_create

  部分, 設定跟蹤結果的儲存檔案(用語句跟蹤的時候, 跟蹤結果只能儲存到檔案)

  然後, 在需要跟蹤的時候, 運行這個指令碼來啟動跟蹤

  啟動跟蹤後, 跟蹤自動進行, 所以你可以關閉查詢分析器做其他事情去了.

  三、已知的問題

  1. 追蹤記錄不是即時寫入追蹤檔案的, 因此, 可能會到你停止跟蹤的時候, 跟蹤資訊才寫入追蹤檔案

  2. 查看當前已經進行的跟蹤可以用(關於結果集的解釋, 請看線上說明):


  select * FROM ::fn_trace_getinfo(0)

  3. 停止某個跟蹤, 可以在sp_trace_create 語句中設定自動停止時間, 也可以手動停止跟蹤, 用下面的語句: 


exec sp_trace_setstatus @traceid = 1 , -- 跟蹤的id @status = 0 -- 停止, 這樣以後還可能指定此項為來啟用 exec sp_trace_setstatus @traceid = 1 , @status = 2 -- 關閉, 徹底釋放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.