2013. 9. 13. 10:27

Tempdb 공간 사용 확인

SQL 2005 이상

 

http://www.madeira.co.il/troubleshooting-tempdb-space-usage/ 발췌

 

Tempdb is a critical resource in SQL Server. It is used internally by the database engine for many operations, and it might consume a lot of disk space. In the past two weeks I encountered 3 different scenarios in which tempdb has grown very large, so I decided to write about troubleshooting such scenarios.
Before I describe the methods for troubleshooting tempdb space usage, let’s begin with an overview of the types of objects that consume space in tempdb. There are 3 types of objects stored in tempdb:

  • User Objects
  • Internal Objects
  • Version Stores 

A user object can be a temporary table, a table variable or a table returned by a table-valued function. It can also be a regular table created in the tempdb database. A common misconception is that table variables (@) do not consume space in tempdb, as opposed to temporary tables (#), because they are only stored in memory. This is not true. But there are two important differences between temporary tables and table variables, when it comes to space usage:

1.     Indexes and statistics on temporary tables also consume space in tempdb, while indexes and statistics on table variables don’t. This is simply because you cannot create indexes or statistics on table variables.

2.     The scope of a temporary table is the session in which it has been created, while the scope of a table variable is the batch in which it has been created. This means that a temporary table consumes space in tempdb as long as the session is still open (or until the table is explicitly dropped), while a table variable’s space in tempdb is deallocated as soon as the batch is ended.

Internal objects are created and managed by SQL Server internally. Their data or metadata cannot be accessed. Here are some examples of internal objects in tempdb:

  • Query Intermediate Results for Hash Operations
  • Sort Intermediate Results
  • Contents of LOB Data Types
  • Query Result of a Static Cursor

Unlike user objects, operations on internal objects in tempdb are not logged, since they do not need to be rolled back. But internal objects do consume space in tempdb. Each internal object occupies at least 9
pages (one IAM page and 8 data pages). tempdb can grow substantially due to internal objects when queries that process large amounts of data are executed on the instance, depending on the nature of the queries.

Version stores are used for storing row versions generated by transactions in any database on the instance. The row versions are required by features such as snapshot isolation, after triggers and online index build. Only when row versioning is required, the row versions will be stored in tempdb.
As long as there are row versions to be stored, a new version store is created in tempdb approximately every minute. These version stores are similar to internal objects in many ways. Their data and metadata cannot be accessed, and operations on them are not logged. The difference is, of-course, the data that is stored in them.

When a transaction that needs to store row versions begins, it stores its row versions in the current version store (the one that has been created in the last minute). This transaction will continue to store row versions in the same version store as long as it’s running, even if it will run for 10 minutes. So the size of each version store is determined by the number and duration of transactions that began in the relevant minute, and also by the amount of data modified by those transactions.

Version stores that are not needed anymore are deallocated periodically by a background process. This process deallocates complete version stores, not individual row versions. So, in some cases, it might take a while till some version store is deallocated.
There are two types of version stores. One type is used to store row versions for tables that undergo online index build operations. The second type is used for all other scenarios.

 

 

 

 

-- 실행되는 구문의 temp page allocate
select task.session_id, ses.host_name, ses.login_name,ses.login_time
       ,(task.internal_alloc + task.oject_alloc) -(task.internal_dealloc +task.oject_delloc) as used
       ,task.internal_alloc,task.internal_dealloc,task.oject_alloc,task.oject_delloc
    ,object_name(qt.objectid, qt.dbid) as 'spname'
    ,req.cpu_time,req.logical_reads,req.reads, req.writes  
    ,substring(qt.text,req.statement_start_offset/2,
        (case when req.statement_end_offset = -1
        then len(convert(nvarchar(max), qt.text)) * 2
        else req.statement_end_offset end - req.statement_start_offset)/2) as query
    ,req.statement_start_offset, req.statement_end_offset, req.plan_handle, req.sql_handle
from 
       (
             select session_id, request_id
                    ,sum (internal_objects_alloc_page_count) /128 as internal_alloc
                    ,sum (internal_objects_dealloc_page_count)/128 as internal_dealloc 
                                 ,sum (user_objects_alloc_page_count ) /128 as oject_alloc
                                 ,sum (user_objects_dealloc_page_count ) /128 as oject_delloc
              from sys.dm_db_task_space_usage  with (nolock)
             group by session_id, request_id
    ) as task
inner join  sys.dm_exec_requests as req  with (nolock) 
       on task.session_id = req.session_id and task.request_id = req.request_id
inner join sys.dm_exec_sessions as ses with(nolock) on req.session_id = ses.session_id
cross apply sys.dm_exec_sql_text(sql_handle) as qt  
order by (task.internal_alloc + task.oject_alloc) -(task.internal_dealloc +task.oject_delloc) desc, cpu_time desc

테이블 변수도 tempdb의 공간을 사용한다고 되어 있습니다. 알아 두세요

--tempdb 사용 Size
select sum( unallocated_extent_page_count
          + user_object_reserved_page_count
          + internal_object_reserved_page_count
          + mixed_extent_page_count
          + version_store_reserved_page_count ) /128 as [TotalTempDBSizeInMB]
   , sum(unallocated_extent_page_count) /128 as [FreeTempDBSpaceInMB]
from sys.dm_db_file_space_usage 

select
   db_name(su.database_id) dbname
   ,mf.physical_name
   ,(su.unallocated_extent_page_count
   + su.user_object_reserved_page_count
   + su.internal_object_reserved_page_count
   + su.mixed_extent_page_count
   + su.version_store_reserved_page_count ) /128 as total_size_mb
   ,su.user_object_reserved_page_count / 128 user_object_size_mb
   ,su.internal_object_reserved_page_count /128 as internal_object_size_mb
   ,su.unallocated_extent_page_count/ 128 unallocated_extent_size_mb
from sys.dm_db_file_space_usage as su
   join sys.master_files as mf on mf.database_id = su.database_id and mf.file_id = su.file_id

2012. 8. 13. 18:21

실행 쿼리 memory 사용 대기 정보

SQL SERVER 2005 이상. - 일부 컬럼은 SQL 2008 이상



메모리 사용을 대기하는 쿼리의 정보를 반환합니다. 

메모리 대기를 하지 않는 쿼리는 나타나지 않으며, 이 쿼리에 실행되는 내역이 많다면 메모리 할당 대기가 많다는 의미 입니다. 



-- memory used
select top 50
  --mem.session_id,req.group_id, -- sql 2008 이상 가능
  db_name(req.database_id) as db,
  mem.request_time, mem.grant_time,
  mem.granted_memory_kb,mem.used_memory_kb, mem.required_memory_kb, 
  mem.query_cost,mem.timeout_sec,mem.wait_time_ms as 'wait_time',
  object_schema_name(sql_text.objectid,sql_text.dbid) as schema_n,
  object_name(sql_text.objectid, sql_text.dbid) as spname,
  CASE WHEN   req.statement_end_offset = -1 and ( (req.statement_start_offset / 2)  > DATALENGTH (sql_text.text) )
            THEN  convert(varchar(4000), 
                 substring(isnull(sql_text.text, '') 
               , 1, ( ( DATALENGTH (sql_text.text) - 1 )/2 ) + 1 ) )
            ELSE  convert(varchar(4000), substring(isnull(sql_text.text, '') 
             , (req.statement_start_offset / 2) + 1
             , (( case when req.statement_end_offset = -1 then DATALENGTH (sql_text.text) else req.statement_end_offset end 
               - req.statement_start_offset ) /2 ) + 1) )
            END  as query_text,
  ses.login_name, ses.host_name, ses.program_name,
  mem.scheduler_id
from sys.dm_exec_requests as req with (nolock)
  join sys.dm_exec_sessions as ses with (nolock) on req.session_id = ses.session_id
  join sys.dm_exec_query_memory_grants as mem with (nolock) on req.request_id = mem.request_id
    and ses.session_id = mem.session_id
  cross apply sys.dm_exec_sql_text(req.sql_handle) as sql_text
where ses.is_user_process = 1  and wait_type <> 'WAITFOR' 
  --and req.database_id = db_id('tiger')
  -- and mem.grant_time is null -- not allocation 
order by used_memory_kb desc

'Monitoring' 카테고리의 다른 글

Tempdb 공간 사용 확인  (0) 2013.09.13
대랑 I/O 사용 세션 쿼리  (0) 2012.08.13
TEMPDB의 페이지 사용량 측정  (0) 2012.08.13
모니터링::Index 생성 & Rebuild 진행 상황  (0) 2011.12.06
2012. 8. 13. 18:11

대랑 I/O 사용 세션 쿼리

SQL SERVER 2005 이상


1. I/O Pending 조회


-- =====================================
-- I/O pending
-- 어떤 row도 반환되지 않아야 한다.
-- =====================================
select 
    database_id, 
    db_name(database_id) as db_name,
    file_id,
    t2.io_type, 
    io_stall,
    io_pending_ms_ticks,
    scheduler_address 
from  sys.dm_io_virtual_file_stats(NULL, NULL)t1,
        sys.dm_io_pending_io_requests as t2
where t1.file_handle = t2.io_handle


2. 현재 db의 i/o stall 정보


-- ==========================
-- 현재 db의 i/o _io_virtual_file
-- ==========================
declare @db_name sysname
set @db_name = null
select db_name(database_id), file_id ,io_stall_read_ms ,
    cast((io_stall_read_ms+io_stall_write_ms)/(1.0+num_of_reads + num_of_writes) as numeric(10,1)) as 'avg_io_stall_ms' ,
    num_of_reads ,
    cast(io_stall_read_ms/(1.0+num_of_reads) as numeric(10,1)) as 'avg_read_stall_ms' ,
    io_stall_write_ms ,num_of_writes ,
    cast(io_stall_write_ms/(1.0+num_of_writes) as numeric(10,1)) as 'avg_write_stall_ms' ,
    io_stall_read_ms + io_stall_write_ms as io_stalls ,
    num_of_reads + num_of_writes as total_io 
from sys.dm_io_virtual_file_stats(DB_ID(@db_name),null) 
order by avg_io_stall_ms desc


3. 대량의 i/o 사용 쿼리


-- ==========================
-- 대량의 i/o기준 상위
-- ==========================
SELECT TOP 10 qt.dbid,
     object_schema_name(qt.objectid,qt.dbid) + '.' + object_name(qt.objectid,qt.dbid) [object_name],
     (qs.total_logical_reads/execution_count) as avg_logical_reads,
     (qs.total_logical_writes/execution_count) as avg_logical_writes,
     (qs.total_logical_reads + qs.total_logical_writes) / qs.execution_count as [Avg IO],
    substring (qt.text,qs.statement_start_offset/2, 
    (case when qs.statement_end_offset = -1 then len(convert(nvarchar(max), qt.text)) * 2 else qs.statement_end_offset end - qs.statement_start_offset)/2) as query_text, 
    qt.objectid, object_name(qt.objectid) as sp_name
FROM sys.dm_exec_query_stats qs
    cross apply sys.dm_exec_sql_text (qs.sql_handle) as qt ORDER BY [Avg IO] DESC


2012. 8. 13. 17:48

TEMPDB의 페이지 사용량 측정

SQL SERVER 2005 이상



실행 되는 SESSION TEMPDB의 페이지 사용량 측정.

세가지 쿼리다 결과는 같음.


--각 세션별 사용되는 Page, Plan, Statement
WITH BASE AS (
  SELECT session_id, request_id,
 SUM(internal_objects_alloc_page_count) AS [internal object pages alloc used],
 (SUM(internal_objects_alloc_page_count)*1.0/128) AS [internal object alloc space in MB],
 SUM(internal_objects_dealloc_page_count) AS [internal object pages dealloc used],
 (SUM(internal_objects_dealloc_page_count)*1.0/128) AS [internal object dealloc space in MB],
 SUM(user_objects_alloc_page_count) AS [user object pages alloc used],
 (SUM(user_objects_alloc_page_count)*1.0/128) AS [user object alloc space in MB],
 SUM(user_objects_dealloc_page_count) AS [user object pages dealloc used],
 (SUM(user_objects_dealloc_page_count)*1.0/128) AS [user object dealloc space in MB]
  FROM sys.dm_db_task_space_usage 
  GROUP BY session_id, request_id
)
SELECT object_schema_name(R3.objectid,R3.dbid) + '.' + object_name(R3.objectid,R3.dbid) as [object_name], R1.session_id, R1.request_id, 
    R1.[internal object pages alloc used], R1.[internal object alloc space in MB],
 R1.[internal object pages dealloc used], R1.[internal object dealloc space in MB],
 R1.[user object pages alloc used], R1.[user object alloc space in MB],
 R1.[user object pages dealloc used], R1.[user object dealloc space in MB],
    R2.statement_start_offset, R2.statement_end_offset, R4.QUERY_PLAN, R3.text
FROM BASE R1
INNER JOIN sys.dm_exec_requests R2 ON R1.session_id = R2.session_id and R1.request_id = R2.request_id
OUTER APPLY sys.dm_exec_sql_text(R2.sql_handle) AS R3
OUTER APPLY sys.dm_exec_query_plan(R2.plan_handle) AS R4
WHERE R1.session_id > 50
ORDER BY 4 desc

select top 50   
     u.session_id,    
    s.host_name,    
    s.login_name,  
    s.status,  
    s.program_name, 
    sum(u.user_objects_alloc_page_count+u.internal_objects_alloc_page_count)*8 tempdb_space_alloc_kB,    
    sum(u.user_objects_dealloc_page_count+u.internal_objects_dealloc_page_count)*8 tempdb_space_dealloc_kB,   
    sum(u.user_objects_alloc_page_count+u.internal_objects_alloc_page_count -u.user_objects_dealloc_page_count - u.internal_objects_dealloc_page_count)*8 remaining_tempdb_space_alloc_kB    
from sys.dm_db_session_space_usage as u   
    join sys.dm_exec_sessions as s on s.session_id = u.session_id   
where u.database_id = 2   
group by u.session_id, s.host_name,  s.status, s.login_name, s.program_name   
order by 7 desc  
SELECT task.session_id, ses.host_name, ses.login_name
 ,ses.login_time, task.request_id, task.alloc,task.dealloc
    ,object_name(qt.objectid, qt.dbid) as 'SPname'
    ,req.cpu_time,req.logical_reads,req.reads, req.writes  
    ,substring(qt.text,req.statement_start_offset/2,
        (case when req.statement_end_offset = -1
        then len(convert(nvarchar(max), qt.text)) * 2
        else req.statement_end_offset end - req.statement_start_offset)/2) as query
    ,req.statement_start_offset, req.statement_end_offset, req.plan_handle, req.sql_handle
FROM 
       (
             Select session_id, request_id,
                    SUM(internal_objects_alloc_page_count) /128 as alloc,
                    SUM (internal_objects_dealloc_page_count)/128 as dealloc 
              FROM sys.dm_db_task_space_usage  with (nolock)
             GROUP BY session_id, request_id
    ) AS task
inner join  sys.dm_exec_requests AS req  with (nolock) 
       on task.session_id = req.session_id and task.request_id = req.request_id
inner join sys.dm_exec_sessions as ses with(nolock) on req.session_id = ses.session_id
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS qt  
ORDER BY task.alloc DESC


2011. 12. 6. 05:05

모니터링::Index 생성 & Rebuild 진행 상황

SQL SERVER 2005 이상


Index를 생성하거나, Rebuild 작업시 sysprocess 에서  max_dop =  설정값 보다 하나 더 많은 row가 보이면서 완료되어 가면 그 수가 하나씩 줄어드는 것을 확인 할 수 있다.

이 수가 줄어드는 것으로 완료되는 진행 상황을 보았었는데..
sys.partitions에서 작업하는 index_id 값에 해당하는  row 수가  전체 table row 값과 동일할 때까지 증가하는 것을 볼 수 있다.
즉, 완료가 되면 전체 table row 수와 같아 진다.

SQL 2005 이상 부터 가능.

DECLARE @TABLE_NAME SYSNAME, @INDEX_ID INT
SET @TABLE_NAME = 
SET @INDEX_ID = 

-- REBUILD
SELECT A.*, B.ROWS, A.ROWS-B.ROWS AS DIFF_ROWS, B.ROWS*100.0/A.ROWS as '%'
FROM SYS.PARTITIONS A WITH(NOLOCK) JOIN SYS.PARTITIONS B WITH(NOLOCK) 
	ON A.OBJECT_ID=B.OBJECT_ID AND A.INDEX_ID=B.INDEX_ID 
	AND A.PARTITION_NUMBER=B.PARTITION_NUMBER AND A.ROWS<>B.ROWS
WHERE A.OBJECT_ID=OBJECT_ID(@TABLE_NAME)
	AND A.INDEX_ID= @INDEX_ID
	AND A.ROWS-B.ROWS>0
	

-- NEW
SELECT * FROM SYS.PARTITIONS WITH(NOLOCK) WHERE OBJECT_ID = OBJECT_ID(@TABLE_NAME)
SELECT * FROM SYS.SYSPROCESSES WITH(NOLOCK) WHERE SPID = 



'Monitoring' 카테고리의 다른 글

대랑 I/O 사용 세션 쿼리  (0) 2012.08.13
TEMPDB의 페이지 사용량 측정  (0) 2012.08.13
T-SQL:: Default Trace로 DB 증가량 확인  (1) 2011.04.15
Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
2011. 4. 15. 13:23

T-SQL:: Default Trace로 DB 증가량 확인

SQL SERVER 2000 이상

EventClass  : 92, 93, 94, 95 번은 DB File의 증가하거나 Shrink 하는 이벤트 임.
Default Trace가 되고 있는 SQL Server에서는  해당 이벤트를 수집하고 있으며, 증가/축소되는 사이즈를 확인할 수 있다.

begin try  
if (select convert(int,value_in_use) from sys.configurations where name = 'default trace enabled' ) = 1 
begin 
declare @curr_tracefilename varchar(500) ; 
declare @base_tracefilename varchar(500) ; 
declare @indx int ;

select @curr_tracefilename = path from sys.traces where is_default = 1 ; 
set @curr_tracefilename = reverse(@curr_tracefilename);
select @indx  = patindex('%\%', @curr_tracefilename) ;
set @curr_tracefilename = reverse(@curr_tracefilename) ;
set @base_tracefilename = left( @curr_tracefilename,len(@curr_tracefilename) - @indx) + '\log.trc' 


select  @@SERVERNAME as server_name
,	    (dense_rank() over (order by StartTime desc))%2 as l1
,       convert(int, EventClass) as EventClass
,       DatabaseName
,       Filename
,       (Duration/1000) as Duration
,       StartTime
,       EndTime
,       (IntegerData*8.0/1024) as ChangeInSize 
from ::fn_trace_gettable( @base_tracefilename, default ) 
where EventClass >=  92      and EventClass <=  95        and ServerName = @@servername 
order by StartTime desc ;   
end     else    
select -1 as l1, 0 as EventClass, 0 DatabaseName, 0 as Filename, 0 as Duration, 0 as StartTime, 0 as EndTime,0 as ChangeInSize 
end try 
begin catch 
select -100 as l1
,       ERROR_NUMBER() as EventClass
,       ERROR_SEVERITY() DatabaseName
,       ERROR_STATE() as Filename
,       ERROR_MESSAGE() as Duration
,       1 as StartTime, 1 as EndTime,1 as ChangeInSize 
end catch


'Monitoring' 카테고리의 다른 글

TEMPDB의 페이지 사용량 측정  (0) 2012.08.13
모니터링::Index 생성 & Rebuild 진행 상황  (0) 2011.12.06
Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
T_SQL::SP_WHO2 + DBCC  (0) 2010.06.03
2011. 1. 30. 17:10

Admin::Tempdb 의 작업, 모니터링

1.tempdb의 사용

- 지역/전역 임시 테이블과 인덱스, 임시 저장프로시저, 테이블 변수, 커서
- 해시 조인, 집계, 커서, order by , group by , union 쿼리 등과 같이 다양한 작업을 수행하면서 발생되는 중간 결과를 저장하기 위한 임시 테이블
- after트리거, instead of 트리거를 이용할 때 사용되는 개체들 저장
- 대형 xml 개체 저장
- sql server 버전 저장소
- DBCC checkdb 명령을 사용하는 동안에 중간 결과를 정렬 작업을 저장
- 서비스 브로커의 임시 개체를 저장

2. tempdb의 공간 사용

- 내부 개체
- 버전 저장소
- 사용자 개체

3. 최적화 방법

- tempdb의 사용량이 증가할 경우 다른 데이터베이스들의 성능 저하
- tempdb의 사용의 최소화 ( 1번 내용에 해당되는 것들)
- tempdb의 공간을 미리 할당함으로써 자동 증가 옵션 사용을 피함
- 필요하지 않은 경우는 tempdb를 축소하지 말자,  현재 작게 사용하고 있다고 항상 작은 사이즈를 사용하고 있는 것은 아니다. batch 작업이 시작될때는 지금 사용 사이즈 보다 훨씬 많이 사용할 수도 있다. 
- tempdb 데이터 베이스를 물리적 파일로 분리하자, (전형적으로 cpu 코어수 만큼 분리)
- 고속 I/O 하위 시스템에 tempdb를 생성하자  ( RAID 5로는 설정해서는 안된다.: 속도가 느리다.  적어도 RAID 1 또는 RAID10 으로 설정된 I/O 하위 시스템에 생성하는 것을 권장한다.)
- tempdb는 별도의 디스크 드라이브를 가지고 있는 별도의 LUN (논리 단위 번호)에 생성하는 것이 좋다. 
- SQL 2008의 TDE(투명한 데이터 암호화) 사용시 고려해야 한다. tempdb역시 암호화 되기 때문에 디스크 사이를 이동할 때마다 암호화 하고 복호화 하는 작업이 일어난다. 
- 통계 자동 작성, 자동 업데이트 옵션은 활성화 된 상태로 두자
- SQL 2008에서는 CEECKSUM 옵션을 확인하자, SQL 2005에서 업그레이드 되었을 경우에는 비활성화 되어 있다. 꼭 활성화 시키자  - tempdb의 무결성을 보장 할 수 있다. 

4. 모니터링

--1. tempdb SizeSELECT name , db.log_reuse_wait_desc , ls.cntr_value  AS size_kb , lu.cntr_value AS used_kb , CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)    AS used_percent , CASE WHEN CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT) > .5 THEN    CASE     /* tempdb special monitoring */     WHEN db.name = 'tempdb'       AND log_reuse_wait_desc NOT IN ('CHECKPOINT', 'NOTHING') THEN 'WARNING'      /* all other databases, monitor foor the 50% fill case */     WHEN db.name <> 'tempdb' THEN 'WARNING'     ELSE 'OK'     END   ELSE 'OK' END   AS log_status FROM sys.databases db JOIN sys.dm_os_performance_counters lu  ON db.name = lu.instance_name JOIN sys.dm_os_performance_counters ls  ON db.name = ls.instance_name WHERE lu.counter_name LIKE  'Log File(s) Used Size (KB)%' AND ls.counter_name LIKE 'Log File(s) Size (KB)%' -- 2. temdb 사용 session,taskSELECT top 5 * FROM sys.dm_db_session_space_usage  ORDER BY (user_objects_alloc_page_count + internal_objects_alloc_page_count) DESCSELECT top 5 * FROM sys.dm_db_task_space_usageORDER BY (user_objects_alloc_page_count + internal_objects_alloc_page_count) DESCSELECT t1.session_id, t1.request_id, t1.task_alloc,  t1.task_dealloc, t2.sql_handle, t2.statement_start_offset,   t2.statement_end_offset, t2.plan_handleFROM (Select session_id, request_id,    SUM(internal_objects_alloc_page_count) AS task_alloc,    SUM (internal_objects_dealloc_page_count) AS task_dealloc   FROM sys.dm_db_task_space_usage   GROUP BY session_id, request_id) AS t1,   sys.dm_exec_requests AS t2WHERE t1.session_id = t2.session_id  AND (t1.request_id = t2.request_id)ORDER BY t1.task_alloc DESC
--3. 종합
CREATE TABLE tempdb_space_usage ( -- This represents the time when the particular row was -- inserted dt datetime DEFAULT CURRENT_TIMESTAMP, -- session id of the sessions that were active at the time session_id int DEFAULT null, -- this represents the source DMV of information. It can be -- track instance, session or task based allocation information. scope char(7), -- instance level unallocated extent pages in tempdb Instance_unallocated_extent_pages bigint, -- tempdb pages allocated to verstion store version_store_pages bigint, -- tempdb pages allocated to user objects in the instance Instance_userobj_alloc_pages bigint, -- tempdb pages allocated to internal objects in the instance Instance_internalobj_alloc_pages bigint, -- tempdb pages allocated in mixed extents in the instance Instance_mixed_extent_alloc_pages bigint, -- tempdb pages allocated to user obejcts within this sesssion or task. Sess_task_userobj_alloc_pages bigint, -- tempdb user object pages deallocated within this sesssion -- or task. Sess_task_userobj_deallocated_pages bigint, -- tempdb pages allocated to internal objects within this sesssion -- or task Sess_task_internalobj_alloc_pages bigint, -- tempdb internal object pages deallocated within this sesssion or -- task Sess_task_internalobj_deallocated_pages bigint, -- query text for the active query for the task query_text nvarchar(max) )go-- Create a clustered index on time column when the data was collectedCREATE CLUSTERED INDEX cidx ON tempdb_space_usage (dt)goCREATE PROC sp_sampleTempDbSpaceUsage AS Instance level tempdb File space usage for all files within -- tempdb INSERT tempdb_space_usage ( scope, Instance_unallocated_extent_pages, version_store_pages, Instance_userobj_alloc_pages, Instance_internalobj_alloc_pages, Instance_mixed_extent_alloc_pages) SELECT 'instance', SUM(unallocated_extent_page_count), SUM(version_store_reserved_page_count), SUM(user_object_reserved_page_count), SUM(internal_object_reserved_page_count), SUM(mixed_extent_page_count) FROM sys.dm_db_file_space_usage -- 2. tempdb space usage per session -- INSERT tempdb_space_usage ( scope, session_id, Sess_task_userobj_alloc_pages, Sess_task_userobj_deallocated_pages, Sess_task_internalobj_alloc_pages, Sess_task_internalobj_deallocated_pages) SELECT 'session', session_id, user_objects_alloc_page_count, user_objects_dealloc_page_count, internal_objects_alloc_page_count, internal_objects_dealloc_page_count FROM sys.dm_db_session_space_usage WHERE session_id > 50 -- 3. tempdb space usage per active task -- INSERT tempdb_space_usage ( scope, session_id, Sess_task_userobj_alloc_pages, Sess_task_userobj_deallocated_pages, Sess_task_internalobj_alloc_pages, Sess_task_internalobj_deallocated_pages, query_text) SELECT 'task', R1.session_id, R1.user_objects_alloc_page_count, R1.user_objects_dealloc_page_count, R1.internal_objects_alloc_page_count, R1.internal_objects_dealloc_page_count, R3.text FROM sys.dm_db_task_space_usage AS R1 LEFT OUTER JOIN sys.dm_exec_requests AS R2 ON R1.session_id = R2.session_id OUTER APPLY sys.dm_exec_sql_text(R2.sql_handle) AS R3 WHERE R1.session_id > 50go
--5. 결과 쿼리 -- This query reports the maximum allocated space in tempdb over all the data points collectedSELECT CONVERT (float, (MAX(version_store_pages + Instance_userobj_alloc_pages + Instance_internalobj_alloc_pages + Instance_mixed_extent_alloc_pages)))/ 128.0 AS max_tempdb_allocation_MBFROM tempdb_space_usage WHERE scope = ‘instance’
--This query reports the average allocated space in tempdb over all the data points collectedSELECT CONVERT (float, (AVG(version_store_pages + Instance_userobj_alloc_pages + Instance_internalobj_alloc_pages + Instance_mixed_extent_alloc_pages)))/ 128.0 AS avg_tempdb_allocation_MBFROM tempdb_space_usage WHERE scope = ‘instance’
-- 버전 정보 저장 할당양SELECT MAX(version_store_pages) AS max_version_store_pages_allocated, MAX(version_store_pages/128.0) AS max_version_store_allocated_space_MBFROM tempdb_space_usage WHERE scope = ‘instance’
SELECT AVG(version_store_pages) AS max_version_store_pages_allocated, AVG(version_store_pages)/ 128.0 AS max_version_store_allocated_space_MBFROM tempdb_space_usage WHERE scope = ‘instance’
-- top 5 내부 개첵 사용하는 requestSELECT top 5 MAX ((Sess_task_internalobj_alloc_pages) - (Sess_task_internalobj_deallocated_pages)) AS Max_Sess_task_allocated_pages_delta, query_textFROM tempdb_space_usage WHERE scope = 'task' and session_id > 50GROUP BY query_textORDER BY Max_Sess_task_allocated_pages_delta DESCSELECT top 5 AVG ((Sess_task_internalobj_alloc_pages) - (Sess_task_internalobj_deallocated_pages)) AS Avg_Sess_task_allocated_pages_delta, query_textFROM tempdb_space_usage WHERE scope = 'task' and session_id > 50GROUP BY query_textORDER BY Avg_Sess_task_allocated_pages_delta DESC

'Monitoring' 카테고리의 다른 글

모니터링::Index 생성 & Rebuild 진행 상황  (0) 2011.12.06
T-SQL:: Default Trace로 DB 증가량 확인  (1) 2011.04.15
T_SQL::SP_WHO2 + DBCC  (0) 2010.06.03
CPU에 할당된 Task 보기  (1) 2010.03.14
2010. 6. 3. 23:55

T_SQL::SP_WHO2 + DBCC

SQL SERVER 2005 이상
  1. --===================================

  1. -- SP_WHO2와명령어동시확인하기

  1. --===================================

  1.  

  1. SELECT

  1.        ISNULL(D.text, '') AS SQLStatement,

  1.        object_name(D.objectid) AS 'sp_ame',

  1.        A.Session_ID SPID,

  1.        ISNULL(B.status,A.status) AS [Status],

  1.        A.login_name AS [Login],

  1.        ISNULL(A.host_name, '  .') AS HostName,

  1.        ISNULL(CAST(C.BlkBy AS varchar(10)), '  .') AS BlkBy,

  1.        DB_NAME(B.Database_ID) AS DBName,

  1.        B.command,

  1.        ISNULL(B.cpu_time, A.cpu_time) AS CPUTime,

  1.        ISNULL((B.reads + B.writes),(A.reads + A.writes)) AS DiskIO,

  1.        A.last_request_start_time AS LastBatch,

  1.        ISNULL(A.program_name, '') AS ProgramName,

  1.        ISNULL(A.client_interface_name, '') AS ClientInterfaceName

  1. FROM sys.dm_exec_sessions A

  1.        LEFT OUTER JOIN sys.dm_exec_requests B ON A.session_id = B.session_id

  1.        LEFT OUTER JOIN (

  1.              SELECT A.request_session_id SPID, B.blocking_session_id BlkBy

  1.              FROM sys.dm_tran_locks A

  1.                     INNER JOIN sys.dm_os_waiting_tasks B ON A.lock_owner_address = B.resource_address

  1.        ) C ON A.Session_ID = C.SPID

  1.        OUTER APPLY sys.dm_exec_sql_text(B.sql_handle) D

  1. go


 

이 글은 스프링노트에서 작성되었습니다.


'Monitoring' 카테고리의 다른 글

T-SQL:: Default Trace로 DB 증가량 확인  (1) 2011.04.15
Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
CPU에 할당된 Task 보기  (1) 2010.03.14
DBCC FLUSHPROCINDB  (0) 2010.02.04
2010. 3. 14. 15:41

CPU에 할당된 Task 보기

SQL SERVER 2005 이상

 

CPU에 해당하는 Task 보기

select  
	 ss.scheduler_id ,ss.parent_node_id,object_name(sql_text.objectid, sql_text.dbid)  as 'SP명'
	,ses.session_id , ses.host_name , ses.program_name , ses.client_interface_name 
	,ses.login_name 
	 ,substring(sql_text.text,sr.statement_start_offset/2,
			(case when sr.statement_end_offset = -1
			then len(convert(nvarchar(max), sql_text.text)) * 2
			else sr.statement_end_offset end - sr.statement_start_offset)/2) as query
from sys.dm_os_schedulers as ss with (nolock) 
inner join sys.dm_os_tasks as st with (nolock) on ss.scheduler_id = st.scheduler_id
inner join sys.dm_exec_requests as sr with (nolock) on st.request_id = sr.request_id
inner join sys.dm_exec_sessions as ses with (nolock) on sr.session_id = ses.session_id 
cross apply sys.dm_exec_sql_text(sr.sql_handle) as sql_text
-- where ss.parent_node_id = 2 -- numa 노드에서 실행되는 쿼리
-- where ss.scheduler_id = 24  -- cpu 스케줄에 할당된 쿼리
 


'Monitoring' 카테고리의 다른 글

Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
T_SQL::SP_WHO2 + DBCC  (0) 2010.06.03
DBCC FLUSHPROCINDB  (0) 2010.02.04
DeadLock 발생 원인 찾기  (0) 2009.07.20
2010. 2. 4. 20:48

DBCC FLUSHPROCINDB


SQL SERVER 2000 이상

http://sqlblog.com/blogs/kalen_delaney/archive/2007/09/29/geek-city-clearing-a-single-plan-from-cache.aspx

 

 

DBCC FREESYSTEMCACHE(TokenAndPermUserStore)    

--보안 캐쉬를 제거

 

DBCC FREESYSTEMCACHE    

--사용하지 않는 항목을 모든 캐시에서 직접 제거

 

DBCC FREEPROCCACHE

--프로시져 캐시에서 모든 요소를 제거

 

DBCC FLUSHPROCINDB (dbid)

--지정한 데이터베이스에 있는 스토어드 프로시저 캐시를 제거

 

'Monitoring' 카테고리의 다른 글

Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
T_SQL::SP_WHO2 + DBCC  (0) 2010.06.03
CPU에 할당된 Task 보기  (1) 2010.03.14
DeadLock 발생 원인 찾기  (0) 2009.07.20
2009. 7. 20. 17:17

DeadLock 발생 원인 찾기


Deadlock 발생시 원인과 해결법.

 

1. Deadlock 이유를 알고 싶으면 trace 1204 를 켜 준다.

DBCC traceon(1204,-1)

DBCC Tracestatus(-1) -- 잘 실행되고 있는지 확인

 

2. Deadlock 발생되면 SQL의 에러로그에 로그가 남게 된다.

Deadlock encountered .... Printing deadlock information
Wait-for graph
Node:1 PAG: 9:1:18061 CleanCnt:2 Mode: SIU Flags: 0x2
Grant List 1::
Grant List 2::
Owner:0x27c007e0 Mode: S Flg:0x0 Ref:0 Life:00000001 SPID:84 ECID:0
SPID: 84 ECID: 0 Statement Type: UPDATE Line #: 11
Input Buf: RPC Event: dbo.Example_Stored_proc
Requested By: 0
ResType:LockOwner Stype:'OR' Mode: IX SPID:78 ECID:0 Ec:(0x44AA55F0) Value:0x3affcd00 Cost:(0/0)
Node:2 PAG: 9:1:18134 CleanCnt:2 Mode: SIU Flags: 0x2
Grant List 1::
Owner:0x28e6f060 Mode: S Flg:0x0 Ref:0 Life:00000001 SPID:78 ECID:0
SPID: 78 ECID: 0 Statement Type: UPDATE Line #: 11
Input Buf: RPC Event: dbo. Example_Stored_proc
Grant List 2::
Requested By:
ResType:LockOwner Stype:'OR' Mode: IX SPID:84 ECID:0 Ec:(0x239955F0) Value:0x3affc940 Cost:(0/0)
Victim Resource Owner:
ResType:LockOwner

Stype:'OR' Mode: IX SPID:84 ECID:0 Ec:(0x239955F0) Value:0x3affc940 Cost

 

3.  에러로그를 확인해 보면 'Example_stored_proc'  프로시저에서 update 시 exclusive lock  이 발생하고 있다는 것을 확인 할 수 있다.

 

4. sp_helptext 'Example_stored_proc'  를 실행하여 프로시저의 내용을 확인 한다.

 

5. 이와 관련있는 프로시저를 확인하고 deadlock 이 발생하는 page를 확인할 수 있다.

Node:1 PAG: 9:1:18061 CleanCnt:2 Mode: SIU Flags: 0x2

 

6. 해당 페이지를 조사해 본다. , DBCC Page 사용

MSDN : http://support.microsoft.com/kb/83065

 

DBCC page(9,1,18061,0)


PAGE: (1:18061)
---------------
BUFFER:
-------
BUF @0x01665900
---------------
bpage = 0x1DF58000 bhash = 0x00000000 bpageno = (1:18061)
bdbid = 9 breferences = 1 bstat = 0xb
bspin = 0 bnext = 0x00000000
PAGE HEADER:
------------
Page @0x1DF58000
----------------
m_pageId = (1:18061) m_headerVersion = 1 m_type = 1
m_typeFlagBits = 0x0 m_level = 0 m_flagBits = 0x8000
m_objId = 1013578649 m_indexId = 0 m_prevPage = (0:0)
m_nextPage = (0:0) pminlen = 52 m_slotCnt = 82
m_freeCnt = 3075 m_freeData = 5009 m_reservedCnt = 0
m_lsn = (2689:87968:2) m_xactReserved = 0 m_xdesId = (0:0)
m_ghostRecCnt = 0 m_tornBits = 0
.................

object_id를 알아 낼 수 있다.

 

7.  object 확인

 

Use DBNAME
Select object_name(OBJECT_ID)


8. 프로시저에서 해당 object를 확인하고  update 문을 찾아 그대로 update 테스트 해 본다.

이때, 해당 컬럼에 인덱스가 있는지 확인 한다. update 시 인덱스가 없으면 table scan 을 하게되고 exclusive lock 이 발생한다.

 

9. Key 되는 컬럼에 인덱스를 생성 해 준다.

 

10. 후에 다시 실행해봐서 deadlock 이 발생하는지 확인 한다.


 


 


'Monitoring' 카테고리의 다른 글

Admin::Tempdb 의 작업, 모니터링  (0) 2011.01.30
T_SQL::SP_WHO2 + DBCC  (0) 2010.06.03
CPU에 할당된 Task 보기  (1) 2010.03.14
DBCC FLUSHPROCINDB  (0) 2010.02.04