4

我正在尝试为我在 SQL Server 2008 中的数据库上进行的操作调整一些机制。

为了选择我经常使用的问题的最佳方法SET STATISTICS IO ON,但是当我将一长串语句与另一个语句进行比较时,它并不是很方便。

因此,例如,我怎么知道 T-SQL 语句所需的全部读/写,如下所示:

WHILE @i < 1000
BEGIN
 <some statements>
 SET @I = @I + 1
END

感谢您的帮助(请原谅我英语不好)。

4

2 回答 2

0

如何使用动态管理视图sys.dm_exec_query_stats而不是SET STATISTICS IO

IF EXISTS (SELECT * FROM sys.tables WHERE name = 'Read_and_Write') 
  DROP TABLE Read_and_Write

CREATE TABLE Read_and_Write (
  RowID INT NOT NULL,
  RowValue CHAR(2000)
) 

CHECKPOINT
GO
DBCC DROPCLEANBUFFERS
GO
DBCC FREEPROCCACHE 
GO

INSERT Read_and_Write (RowID, RowValue) 
SELECT TOP 10000
  ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
  'X'
FROM sys.all_objects s1 CROSS JOIN sys.all_objects s2 

SELECT COUNT(*)
FROM Read_and_Write
WHERE RowID <= 500

SELECT 
  cast( (select [processing-instruction(q)] = 
  case when [sql_handle] is null then ''
       else (substring(s.text,(q.statement_start_offset + 2) / 2,
     (case when q.statement_end_offset = -1 
           then len(convert(nvarchar(max),s.text)) * 2
           else q.statement_end_offset
      end - q.statement_start_offset) / 2))
  end for xml path('') ) as xml) AS sql_text,
  last_worker_time,
  last_elapsed_time,
  last_logical_reads,
  last_physical_reads,
  last_logical_writes,
  last_rows,
  p.query_plan
FROM sys.dm_exec_query_stats q
CROSS APPLY sys.dm_exec_sql_text([sql_handle]) s
CROSS APPLY sys.dm_exec_query_plan ([plan_handle]) p
于 2012-12-27T22:21:23.563 回答
0

您可以创建一个表变量,并在其中跟踪代码部分执行时的持续时间。

例如:

DECLARE @Tracking TAABLE
(
    ID int IDENTITY (1, 1) PRIMARY KEY NOT NULL,
    TheStep varchar(50),
    Start datetime,
    End datetime
)

DECLARE
    @TheStep varchar(50),
    @Start datetime,
    @End datetime

-- first block of code to track

SET @TheStep = 'Grab data from MyTable.'
SET @Start = getdate()

SELECT * FROM MyTable

SET @End = getdate()

INSERT INTO @Tracking (TheStep, Start, End)
SELECT @TheStep, @Start, @End

-- reset variables for next batch of commands to measure
SELECT @TheStep = NULL, @Start = NULL, @End = NULL

-- after all is said and done, display the results along with duration (ms) for each.
SELECT TheStep, DATEDIFF(ms, Start, End)
FROM @Tracking
于 2012-12-27T19:01:33.597 回答