블로그 이미지
SQL Server VS. 석이 minsouk@hotmail.com MSSQL 쿼리성능 관련해 궁금한 사항이 있다면 언제나 누구나 TeamViewer + Line (네이버 japan 메신저) 에 minsouk1 추가 후 연락주세요~ 010-9967-0955 보미아빠

카테고리

보미아빠, 석이 (448)
밥벌이 (16)
싸이클 (1)
일상 (1)
Total213,370
Today6
Yesterday49

달력

« » 2018.07
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        

공지사항

부하 데이터생성

밥벌이 / 2010.11.18 16:05

if object_id('sm_cpu_pfmnc_log') is not null
drop table sm_cpu_pfmnc_log
go

create table sm_cpu_pfmnc_log
(
     host_id              CHARACTER VARYING(13)
,     log_ocr_ymdt         datetime
,     cpu_idx              SMALLINT
,     used_rto             NUMERIC(20,2)
,     idel_rto             NUMERIC(20,2)
,     user_rto             NUMERIC(20,2)
,     sys_rto              NUMERIC(20,2)
,     nice_rto             NUMERIC(20,2)
,     irq_rto              NUMERIC(20,2)
,     softirq_rto          NUMERIC(20,2)
,     io_wait_rto          NUMERIC(20,2)
,     prv_mde_exec_tm_rto  NUMERIC(20,2)
,     dly_pcd_call_tm_rto  NUMERIC(20,2)
)

--select * from sm_cpu_pfmnc_log

;with nums as (
select 0 a union all select 1 union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
)
, mm as (select a.a+b.a*10 mm from nums a ,nums b where a.a+b.a*10 < 60)
, hh as (select a.a+b.a*10 hh from nums a ,nums b where a.a+b.a*10 < 24)
, hostname as (select a.a+b.a*10+c.a*100+d.a*1000 hostname from nums a, nums b, nums c, nums d where a.a+b.a*10+c.a*100+d.a*1000 < 2)
insert into sm_cpu_pfmnc_log
select right('000000000000000'+cast(hostname as varchar(100)), 13) host_id
  , dateadd(hh, hh, dateadd(mi, mm , getdate())) log_ocr_ymdt
  , hh % 8 cpu_idx
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) used_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) idel_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) user_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) sys_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) nice_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) irq_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) softirq_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) io_wait_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) prv_mde_exec_tm_rto
  , cast(abs(checksum(newid()))/3.33 as numeric(20,2)) dly_pcd_call_tm_rto
  from hostname, hh, mm
order by 2

-- 아래와 같이 파일로 생성
select right(cast(used_rto as varchar(20)),5), * from sm_cpu_pfmnc_log order by log_ocr_ymdt
-- 생성된 파일을 array insert 하기로 함

Posted by 보미아빠

Array Insert

밥벌이 / 2010.11.17 18:26
46배 빨라지면 쓸만한가?






Begin tran Commit tran 은 빼고 Test 하시길 바랍니다.

alter database t set recovery simple with rollback immediate
go

if object_id ('tblx') is not null
drop table tblx
go

create table tblx
(c1 int
,c2 int
,c3 int
,c4 int
,c5 int
,c6 int
,c7 int
,c8 int
,c9 int
,c10 int
,c11 int
,c12 int
,c13 int
,c14 int
,c15 int
)
go

declare
  @total_loop_count int = 100000
 ,@current_loop_count int = 0
 ,@array_insert int = 0
 ,@start_time datetime2 = getdate()
 ,@end_time datetime2 = getdate()

begin tran
while (1=1) begin
 if @array_insert = 1 begin
  insert into tblx values
       (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
        , (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
  set @current_loop_count += 10
  print @current_loop_count
  if @current_loop_count >= @total_loop_count break;
 end else begin
  insert into tblx values
       (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
  set @current_loop_count += 1
  print @current_loop_count
  if @current_loop_count >= @total_loop_count break;
 end
end
commit tran

select datediff(second, @start_time, getdate()) '입력시간 sec'

'밥벌이' 카테고리의 다른 글

민석이의 waitstat 모니터링  (0) 2010.11.18
부하 데이터생성  (0) 2010.11.18
Array Insert  (1) 2010.11.17
이 쿼리의 결과는 뭘까요?  (6) 2010.11.04
insert select 로 인해 플랜 공간이 소모됩니다.  (0) 2010.10.28
insert 속도를 높여보자  (1) 2010.10.18
Posted by 보미아빠

무릎통증과 싸이클링...^^

 

무릎통증과 싸이클링

사이클링은 무릎통증을 악화시키는 것과는 거리가 멀다.

사이클링은 오히려 손상된 무릎관절의 회복에 좋은 것으로 알려져 있다.

무릎 손상으로 달리기나 걷기가 금지되더라도 페달링은 가능할 수 있다.

그러나 이러한 사실에도 불구하고 무릎 손상은 라이딩 중에 간혹 있을 수 있는 일이다.

사이클링이 무릎에 미치는 영향의 독특한 점은 수많은 반복운동에 의한 것이다.

90회전의 평균적인 rpm이면 한시간에 5400회전이 된다.

이것은 인대와 연골에 큰 자극이 된다.

각 회전시마다 무릎관절은 몇 개의 평면상에서 미끄러지고 회전한다.

 이러한 과정에서 안장의 위치나 클리트의 위치가 적절치 않으면 문제가 발생할 수 있다.

도로싸이클은 산악주행보다 무릎에 더 위험할 수 있다.

이것은 고정된 위치에서의 반복적인 운동 때문이다.
이와 같이 반복적인 싸이클링을 통해 무릎이 강해지느냐 아니면 손상되느냐 하는 것은

싸이클링의 올바른 자세를 얼마나 잘 알고 있는지에 달려있다.

좋은 세팅

먼저 당신 자전거의 세팅을 완벽하게 하여야 한다.

이것은 초보자에게만 국한된 일이 아니다.

숙련된 라이더도 새 자전거를 세팅할 때 실수를 할 수 있다.

1. 당신의 다리길이(inseam size)에 0.883을 곱하면 일반적인 BB중심부터 안장 윗면까지의 길이가 된다.

   그러나 이것은 단지 시작점에 불과하다.

   당신의 경험에 따라 약간의 변위가 가능하다.

   예를들어 발이 큰 라이더는 안장높이를 더 높이는 것이좋다. (반대도 마찬가지..)

2. 안장이 높으면 무릎 뒤쪽의 통증을 유발하기 쉬우며, 안장이 낮으면 무릎 앞쪽의 통증을 유발하기 쉽다.

3. 안장의 앞 뒤 위치에 대하여는 자전거에 올라타서 크랭크암을 수평으로 위치하였을 때

   무릎의 중심과 페달의 중심이 수직선   상에 위치해야 한다.

   따라서 무릎 바로 앞에서 실에 매달은 추를 늘어뜨리면 크랭크암의 끝에 위치하도록 한다.*


4. 클리트 위치를 세팅하는 것은 무릎 통증에 매우 중요한 요소이다. 

   잘못된 클리트 위치는 무릎 통증의 가장 큰 원인이다.
   예전 토클립을 사용하던 시대에는 무릎 통증이 지금처럼 많지 않았다.

   지금의 슈즈와 클리트는 정확한 세팅이 필수적이다.
   무릎 통증이 예상되는 경우에는 적어도 좌우 6도~15도의 회전이 가능한 클리트가 권장된다.

주* 일반적으로 크랭크암이 수평일 때 가장 큰 힘을 낼 수 있습니다.
이 위치에서 무릎관절과 페달 중심이 수직선에 위치하게 되면 무릎 관절이 미끄러지는 힘이 발생되지 않습니다.

그러나 수직선 위치에서 벗어나게 되면 무릎이 펴지거나 접혀지면서 힘이 발생됩니다.

이는 무릎의 스트레스를 증가시키는 요인이 되는 것입니다.

이러한 이유 때문에 위와 같은 세팅이 권장되는 것이 아닐까 생각합니다.

무릎 통증을 예방하고 완화시키기 위한 Tips

1. 무릎을 따뜻하게
   추운 날씨에는 무릎을 덮어주어야 한다.
   간혹 추운 날씨에 반바지 차림으로 주행을 하더라도 문제가 없는 사람들도 있다.

   이것에 관하여는 개인차가 클 수 있다.

2. 워밍업
   최소한 15분의 점차적인 워밍업이 필요하다.

   혈액순환을 위해 부드러운 페달링으로 시작하라.

3. 힘보다는 회전수로
   숙련된 프로 선수는 완만한 업힐이나 타임트라이얼의 경우에도 100rpm에 가까운 페달링을 유지한다.

   무릎 통증 완화를 위해서는 평소보다 낮은 기어비와 높은 회전수로 언덕을 오르도록 하라.

4. 주행거리를 천천히 증가시켜라
   특히 봄철에 훈련량을 급격히 증가시키지 않도록 유의해야 한다.

   1주일간의 주행거리를 지난주에 비해 10%이상 증가시키지 않는 것이 권장된다.

5. 변화에 주의하라
   셋팅을 바꾸거나 장비를 바꾸었을 때 적응기간을 두어야 한다.

   예를 들어 타임 트라이얼을 위해 크랭크암의 길이를 늘렸거나

   BB폭이 넓은 텐덤 자전거를 처음 탔을 때 무릎의 불편함을 느낄 수 있다.

6. 트랙용 고정기어 자전거 주행을 삼가라.
   무릎 통증이 있을 때는 트랙용 자전거 주행을 삼가야 한다.

   브레이크가 없는 트랙용 자전거는 속도를 줄이기 위해

   페달의 움직임에 저항해야 하는데 이것은 종지뼈에 무리를 준다.

7. 댄싱

   앉은 상태에서 무리하게 언덕을 주행하지 말아야 한다.

   언덕에서 페달링 rpm이 떨어지면 가능한 안장에서 일어서서 주행하도록 해야 한다.

   낮은 페달링의 강한 힘으로 앉아서 주행하는 것을 삼가야 한다.

8. 고정 클리트를 사용하지 말라.
    최상의 자연스러운 각도를 찾아갈 수 있도록 고정 클리트를 사용하지 않는 것이좋다.

9. 스쿼트 운동에 주의하라
   스쿼트 운동시에 무릎의 각도를 155도에서 90도 사이로 유지하는 것이 좋다.

10. 달리기
     경사진 곳에서 달리는 것을 삼가라.

     특히 내리막길을 뛰어내려가는 것은 큰 압박을 준다.

 

 

===========================================================================================
통증과 그 해소법

앞무릎 통증
안장이 너무 낮은 경우, 과한 언덕훈련, 너무 높은 기어를 스핀하는 경우 발생한다.
한쪽 무릎에만 통증이 있을 경우 양쪽 다리길이에 차이가 있는 경우일 수 있다.

시즌 초반 훈련양을 급격히 중가시킬때 발생할 수도 있다.


[해소책] 안장 높이를 높혀서, 발이 다운스트록 정점에 있을때 무릎 굴절각이 25도 이상 되지 않도록 하라.

그리고 기어를 낮춰 쉬운 기어를 스핀하며, 증상이 없어 질때 까지는 언덕을 피한다.

 floating 클릿을 사용하고, 크랭크와 페달사이에 스페이서를 넣거나, BB축이 좀 더 긴것을 사용하라.

양다리 길이가 다를 때는 안장 높이를 긴 다리에 맞추고, 짧은 다리쪽 클릿 밑에 얇은 판을 대어 다리길이를 같게 만든다.

뒷무릎 통증
안장이 너무 높고, 너무 안장 뒷부분에 앉으며, 햄스트링이 유연하지 않고,

페달링을 할 때 발 뒷꿈치를 너무 아래로 떨어트리고, 너무 높은 기어를 사용할 때,

클릿이 너무 많이 좌우로 움직일 때, 햄스트링과 quadriceps 간 근육 불균형이 있을 때 발생한다.

[해소책] 안장 앞부분에 앉고, 안장높이를 낮추어라. 높은 기어를 스핀하거나 언덕훈련을 할 때, 발 뒷꿈치를 떨어뜨리지 말라. 클릿의 좌우 움직임은 5도 정도로 제한하라. 바이크 위에서 자주 스트레치 하라.

내측 옆무릎 통증
발끝이 바깥쪽으로 향하고, 양 무릎을 너무 밖으로 벌리고 페달링하는 경우 발생한다.

[해소책] 고정식 클릿을 사용하는 경우, 발끝이 안쪽으로 향하도록 클릿을 조정하여

내측 인대의 부담을 줄어 준다. floating 클릿을 사용하는 경우,

좌우로 움직이는 범위를 5도로 제한하라.

BB축의 길이를 줄이는 것을 검토하라.

주행거리를 줄이고, 쉬운 기어를 스핀하라. 달리기와 스키타는 것을 피하라.


외측 옆무릎 통증
클릿이 잘못 조정되어 발끝이 안쪽으로 향할때 오는 통증이다.

또한 BB축의 길이가 너무 짧은 경우, 안장 높이가 낮은 경우,

너무 높은 기어를 스핀하는 경우, 너무 과한 언덕 훈련을 할 경우 발생할 수 있다.

[해소책] 발끝이 약간 밖으로 향하도록 클릿을 조정하고, floating 클릿을 쓰되,

좌우 운동범위는 5도로 제한한다. BB축의 길이가 긴 것을 써 무릎과 무릎사이를 넓힌다.

또는 페달과 크랭크 사이에 스페이서를 삽입할 수도 있다.

안장높이를 약간 높이고, 양다리 길이가 서로 다른지도 체크해 보라. 언덕을 피하고, 주행거리를 줄여라. 

'싸이클' 카테고리의 다른 글

무릎통증.....뒷무릎이 넘 아파~  (0) 2010.11.16
Posted by 보미아빠

select *
  from tblx a
  left join tbly b
    on a.idx = b.idx
   and a.idx in (1,2)
   and b.col1 = 10


이거라고 생각하는가?



if object_id('tblx') is not null
drop table tblx
go

if object_id('tbly') is not null
drop table tbly
go

create table tblx
(idx int
,col1 int
,col2 int
)
go

insert into tblx values (1,10,100)
insert into tblx values (2,20,200)
insert into tblx values (3,30,300)
insert into tblx values (4,40,400)
insert into tblx values (5,50,500)

go

create table tbly
(idx int
,col1 int
,col2 int
)
go

insert into tbly values (1,10,100)
insert into tbly values (2,20,200)
insert into tbly values (3,30,300)
go

내가 위 질문을 했을때 10명에 1명도 답을 못하더라....... 이는 sql join 의 on 과 where 를 아직도 이해하지 못하고 마구 쓰는 사람이 대부분 이라는 것이다. 심심하면 당신이 일하는 회사의 sql 팀장에게 문의해 봐라....모르는 사람도 있을듯 하다.

create database l
go

use l
go
if object_id ('tblx') is not null
drop table tblx
go

create table tblx
(idx int
,c1 int
,c2 int
)
go

if object_id ('tbly') is not null
drop table tbly
go

create table tbly
(idx int
,c1 int
,c2 int
)
go

insert into tblx values (1,1,1),(2,2,1),(3,null,1),(4,4,null)
insert into tbly values (1,1,1),(2,2,1),(4,4,null)
go

--exec sp_dbcmptlevel l, 80

select *
  from tblx a, tbly b
 where a.idx *= b.idx
   and (b.idx = 1 or b.idx is null)
  
이건 이렇게 풀 수 있다.

select *
  from tblx a
  left join tbly b
    on a.idx = b.idx
   and (b.idx = 1 or b.idx is null)

다음의 경우를 생각해 보자.
   
select *
  from tblx a
  left join tbly b
    on a.idx = b.idx
 where b.idx = 1
    or b.idx is null
   
위 쿼리를 tsql 조인으로 해보라 결과가 나오지 않는다.

select *
  from tblx a, tbly b
 where a.idx *= b.idx
   and (b.idx = 1 or b.idx is null)

이렇게 풀 수 밖에 없다. 이건 불편하다.

select *
  from (select a.*, b.idx bidx, b.c1 bc1, b.c2 bc2
    from tblx a, tbly b
   where a.idx *= b.idx) a
 where bidx = 1 or bidx is null
     
     
정의를 내려보면 다음과 같다.

- ansi left outer join 에서 on 절에는 join 조건을 기술하고 where 조건은 필터를 표시한다. 그러므로 어떠한 경우에도 명확하게 표현할 수 있다.  

 

- tsql *= (left join) 은 driving table 의 조건은 filter 조건이고, drived 되는 테이블의 조건은 join 조건으로만 풀려 drived 되는 테이블을 필터로 풀 수 없는 문제가 있게된다. 이러한 불편을 해소하기 위해 tsql *= (outer join) 을 sql 서버에서 차기 버전부터 지원하지 않기로 한 것이다. work around 로 tsql *= 에서 inline view 를 같이 쓰면 drived 되는 테이블의 filter 조건을 명시 할 수 있다.

 

- 따라서 이것을 누구처럼 먼저하고 저것을 먼저하고 라고 해석하면 안된다.  


Posted by 보미아빠

아래와 같이 해결 가능하다.
(이건 모 sql 모니터링 업체에서 질문한 내용입니다.)

if object_id ('tblx') is not null
drop table tblx
go

create table tblx
(idx int)
go

insert into tblx (idx) select 1 union all select 2
go
insert into tblx (idx) select 2 union all select 3
go
--syscacheobjects sql
--insert into tblx (idx) select 1 union all select 2

insert into tblx values(1),(2)
go
insert into tblx values(2),(3)
go
--syscacheobjects sql
--(@1 int,@2 int)INSERT INTO [tblx] values(@1),(@2)


dbcc freeproccache
select * from master.dbo.syscacheobjects

Posted by 보미아빠


로킹 시스템 DB 아키텍팅이라는 새로운 업무를 진행중이다. 
어떻게 하면 가장 빠르게 데이터를 넣을 수 있고,
어떻게 하면 가장 빠르게 데이터를 인출 할 수 있을 것인가에 대한 고민이다.

먼저 데이터 삽입에 대해서는 이러한 방법이 테스트의 대상이 될 듯 하다.

방법1
insert into tblx values (1,'minsouk')
go
insert into tblx values (2,'eunkyoung')
go
insert into tblx values (3,'bomi')
go

방법2
begin tran
   insert into tblx values (1,'minsouk')
   go
   insert into tblx values (2,'eunkyoung')
   go
   insert into tblx values (3,'bomi')
   go
commit tran

방법3

if object_id('usp_insert_tblx') is null
exec ('create proc usp_insert_tblx as select 1')
go

alter proc usp_insert_tblx
 @idx int
,@cname varchar(200)
as
insert into tblx values(@idx, @cname)
go

exec usp_insert_tblx 1, 'minsouk'
go
exec usp_insert_tblx 2, 'eunkyoung'
go
exec usp_insert_tblx 3, 'bomi'
go

방법4
begin tran
   exec usp_insert_tblx 1, 'minsouk'
   go
   exec usp_insert_tblx 2, 'eunkyoung'
   go
   exec usp_insert_tblx 3, 'bomi'
   go
commit tran

방법5
sqlcli를 테이블 변수 이용

방법6
insert into tblx values (1,'minsouk'), (2,'eunkyoung'), (3,'bomi')

글을 읽고있는 당신은 무엇이 가장 빠르다고 생각되는가?
더 빠르게 넣을 수 있는 방법이 있다고 생각하는가?
단 쿼리문의 변경과 insert 하는 방법론으로만 이야기를 한정 하고자 한다.
로그 디스크를 어떻게 구성하고 등등은 2부로 하자.

Posted by 보미아빠

sp_reset_connection 이 무엇을 하는가? 또 무엇을 하지 못하는가?

sp_reset_connection resets the following aspects of a connection:

It resets all error states and numbers (like @@error)
It stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
It will wait for any outstanding I/O operations that is outstanding
It will free any held buffers on the server by the connection
It will unlock any buffer resources that are used by the connection
It will release all memory allocated owned by the connection
It will clear any work or temporary tables that are created by the connection
It will kill all global cursors owned by the connection
It will close any open SQL-XML handles that are open
It will delete any open SQL-XML related work tables
It will close all system tables
It will close all user tables
It will drop all temporary objects
It will abort open transactions
It will defect from a distributed transaction when enlisted
It will decrement the reference count for users in current database; which release shared database lock
It will free acquired locks
It will releases any handles that may have been acquired
It will reset all SET options to the default values
It will reset the @@rowcount value
It will reset the @@identity value
It will reset any session level trace options using dbcc traceon()

sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
If you entered an application role using sp_setapprole, since application roles can not be reverted

Note: Pasting the content as I do not want it to be lost in the ever transient web

logon trigger 의 발동

sp_reset_connection 이 발생되면, logon trigger 도 동작하게 된다 예전에는 sp_reset_connection 을 호출 하지 않을 방법이 있었지만, 해당 옵션은 버전이 올라가면서 제거 되었다. logon trigger 는 시간으로도 접근제어가 가능하도록 디자인 되어 있어 sp_reset_connection 이 발생 할때마다 체크 되도록 되어 있다. (by design)

linked server 연결에서 logon trigger 가 문제인데, sp_reset_connection 을 호출 하지 않게 할 수 없나?

있다. 다음과 같이 다른 방식으로 연결하면 사용하지 않는다.

-- 기존 전통적인 방식
EXEC master.dbo.sp_addlinkedserver @server = N'TEST1', @srvproduct=N'SQL Server'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'TEST1',@useself=N'False',@locallogin=NULL,@rmtuser=N'sqler',@rmtpassword='!1234'


-- login logout 을 하지 않기 위해서 아래와 같이 odbc 를 사용합니다.
EXEC master.dbo.sp_addlinkedserver @server = N'test2', @srvproduct=N' ', @provider=N'MSDASQL', @provstr=N'Driver={SQL Server};Database=master;Server=10.1.1.1;UID=sqler;PWD=!1234;'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'test2',@useself=N'True',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL


while (1=1) begin
 waitfor delay '00:00:00.500'
 select top 1  * from test1.master.dbo.sysprocesses -- 이넘은 login logout 을 계속 합니다.
 --select top 1  * from test2.master.dbo.sysprocesses -- 이건 login logout 을 하지 않습니다.
end


참고자료
http://msdn.microsoft.com/en-us/library/aa172690(v=SQL.80).aspx

다음은 같은 event 로 잡은 프로파일링 데이터 이다.

test1 의 프로파일링
sp_reset_connection 이 발생하고 eventsubclass 에 pooled 라고 찍혀 있다.
여담이지만, sp_reset_connection 은 connection pooling 이 되고 있을때만 발생한다. 이걸보고 login logout 이 생긴다고 pooling 을 사용하지 못한다라고 말하는이가 있거나 오해가 없길 바란다.


test2 의 프로파일링
sp_reset_connection 호출이 없다.


msdasql 을 쓸때 tempdb 나 기타 reset 해야 할 부분이 잘 되는가는 만세가 테스트 하기로 함....
test 할 때 set ansi_nulls default on off 같은걸로 테스트 하면 금방 할끼야~ 리셋 안되야 정상이지 안불렀는데...ㅡ.ㅡ
목적에 따라서 잘 쓰시길 바랍니다.

 

Posted by 보미아빠

SQL Server I/O Basic

밥벌이 / 2010.10.11 13:09


http://technet.microsoft.com/en-us/library/cc966500.aspx
http://technet.microsoft.com/en-us/library/cc917726.aspx
http://blogs.technet.com/b/josebda/archive/2009/03/31/sql-server-2008-i-o-performance.aspx

 

Microsoft SQL Server IO Internals.pptx



읽기의 물리적인 단위는 extents 이고 논리적인 읽기의 단위는 page 이다. 쓰기의 물리적인 단위는 page 이다.
그리고, 823,824 등등 오류의 정의도 볼 수 있다.

Object ID

This is the ID of the object to which the page is assigned within the schema of the database. A page can be assigned to only a single object. When the page is read from disk, the object ID is checked on the page. If the object ID does not match the expected object ID, SQL Server will generate Error 605.

SQL Server often performs its writes on page-sized, 8-KB, or larger boundaries.

Extents

SQL Server generally (except for nonmixed extents) allocates space an extent at a time. An extent is eight 8-KB pages, or 64 KB. SQL Server often performs reads in extent-sized (64 KB or 128 KB) boundaries as well.

Posted by 보미아빠

SQL SERVER TRACEFLAG

분류없음 / 2010.10.08 15:37
http://www.sqlservercentral.com/articles/trace+flags/70131/


flag Trace Flag Description (underlined are sp_configure’able)
-1 Sets trace flags for all connections. Used only with DBCC TRACEON and TRACEOFF. The setting of the Trace flag -1 is not visible with DBCC TRACESTATUS command, but work without problems.
105 SQL Server 6.5 you can use maximum 16 tables or subqueries in a single select statement. There is no documented way, to avoid this restriction, but you can use undocumented trace flag 105 for this purpose.
106 Disables line number information for syntax errors.
107 Interprets numbers with a decimal point as float instead of decimal.
110 Turns off ANSI select characteristics.
204 A backward compatibility switch that enables non-ansi standard behavior. E.g. previously SQL server ignored trailing blanks in the like statement and allowed queries that contained aggregated functions to have items in the group by clause that were not in the select list.
205 Report when a statistics-dependent stored procedure is being recompiled as a result of AutoStat.
206 Provides backward compatibility for the setuser statement.
208 SET QUOTED IDENTIFIER ON.
237 Tells SQL Server to use correlated sub-queries in Non-ANSI standard backward compatibility mode.
242 Provides backward compatibility for correlated subqueries where non-ANSI-standard results are desired.
243 The behavior of SQL Server is now more consistent because null ability checks are made at run time and a null ability violation results in the command terminating and the batch or transaction process continuing.
244 Disables checking for allowed interim constraint violations. By default, SQL Server checks for and allows interim constraint violations. An interim constraint violation is caused by a change that removes the violation such that the constraint is met, all within a single statement and transaction. SQL Server checks for interim constraint violations for self-referencing DELETE statements, INSERT, and multi-row UPDATE statements. This checking requires more work tables. With this trace flag you can disallow interim constraint violations, thus requiring fewer work tables.
246 Derived or NULL columns must be explicitly named in a select….INTO or create view statement when not done they raise an error. This flag avoids that.
253 Prevents ad-hoc query plans to stay in cache.
257 Will invoke a print algorithm on the XML output before returning it to make the XML result more readable.
260 Prints versioning information about extended stored procedure dynamic-link libraries (DLLs). For more information about __GetXpVersion(), see Creating Extended Stored Procedures. Scope: global or session
262 SQL 7 - Trailing spaces are no longer truncated from literal strings in CASE statements. Used after hotfix 891116
302 Should be used with flag 310 to show the actual join ordering. Prints information about whether the statistics page is used, the actual selectivity (if available), and what SQL Server estimated the physical and logical I/O would be for the indexes.
310 Prints information about join order. Index selection information is also available in a more readable format using SET SHOWPLAN_ALL, as described in the SET statement.
320 Disables join-order heuristics used in ANSI joins. To see join-order heuristics use flag 310. SQL Server uses join-order heuristics to reduce the no’ of permutations when using the best join order.
323 Reports on the use of update statements using UPDATE in place. Shows a detailed description of the various update methods used by SQL Server 6.5.
325 Prints information about the cost of using a non-clustered index or a sort to process an ORDER BY clause.
326 Prints information about the estimated & actual costs of sorts. Instructs the server to use arithmetic averaging when calculating density instead of a geometric weighted average when updating statistics.  Useful for building better stats when an index has skew on the leading column.  Use only for updating the stats of a table/index with known skewed data.
330 Enables full output when using the SET SHOWPLAN_ALL option, which gives detailed information about joins.
342 Disables the costing of pseudo-merge joins, thus significantly reducing time spent on the parse for certain types of large, multi-table joins. One can also use SET FORCEPLAN ON to disable the costing of pseudo-merge joins because the query is forced to use the order specified in the FROM clause.
345 Increase the accuracy of choice of optimum order when you join 6 or more tables.
506 Enforces SQL-92 standards regarding null values for comparisons between variables and parameters. Any comparison of variables and parameters that contain a NULL always results in a NULL.
610

SQL 10 – Enable the potential for minimal-logging when:

·   Bulk loading into an empty clustered index, with no nonclustered indexes

·   Bulk loading into a non-empty heap, with no nonclustered indexes

611 After SQL 9 when turned on, each lock escalation is recorded in the SQL Server error log along with the SQL Server handle number.
652 Disables read ahead for the server.
653 Disables read ahead for the current connection.
661 Disables the ghost record removal process. A ghost record is the result of a delete operation. When you delete a record, the deleted record is kept as a ghost record. Later, the deleted record is purged by the ghost record removal process. When you disable this process, the deleted record is not purged. Therefore, the space that the deleted record consumes is not freed. This behavior affects space consumption and the performance of scan operations. SCOPE: Global. If you turn off this trace flag, the ghost record removal process works correctly.
806 Cause 'DBCC-style' page auditing to be performed whenever a database page is read into the buffer pool. This is useful to catch cases where pages are being corrupted in memory and then written out to disk with a new page checksum. When they're read back in the checksum will look correct, but the page is corrupt (because of the previous memory corruption). This page auditing goes someway to catching this - especially on non-Enterprise Edition systems that don't have the 'checksum sniffer'.
809 SQL 8 – Limits the amount of Lazy Write activity.
815 Enables latch enforcement. SQL Server 8 (with service pack 4) and SQL Server 9 can perform latch enforcement for data pages found in the buffer pool cache. Latch enforcement changes the virtual memory protection state while database page status changes from "clean" to "dirty" ("dirty" means modified through INSERT, UPDATE or DELETE operation). If an attempt is made to modify a data page while latch enforcement is set, it causes an exception and creates a mini-dump in SQL Server installation's LOG directory. Microsoft support can examine the contents of such mini-dump to determine the cause of the exception. In order to modify the data page the connection must first acquire a modification latch. Once the data modification latch is acquired the page protection is changed to read-write. Once the modification latch is released the page protection changes back to read-only.
818 SQL 8 enables in memory ring buffer used to track last 2048 successful write operations.
830 SQL 9 – disable the reporting of CPU Drift errors in the SQL Server errorlog like SQL Server has encountered 2 occurrence(s) of I/O requests taking longer than 15 seconds to complete
834 Causes SQL Server to use Windows large-page allocations for the memory that is allocated for the buffer pool. The page size varies depending on the hardware platform, but the page size may be from 2 MB to 16 MB. Large pages are allocated at startup and are kept throughout the lifetime of the process. Trace flag 834 improves performance by increasing the efficiency of the translation look-aside buffer (TLB) in the CPU.
Flag 834 applies only to 64-bit versions of SQL Server. You must have the Lock pages in memory user right to turn on trace flag 834. You can turn on trace flag 834 only at startup.
Trace flag 834 may prevent the server from starting if memory is fragmented and if large pages cannot be allocated. Therefore, trace flag 834 is best suited for servers that are dedicated to SQL Server.
For more information about large-page support, http://msdn2.microsoft.com/en-us/library/aa366720.aspx(http://msdn2.microsoft.com/en-us/library/aa366720.aspx)
835 SQL 9 & 10. For 64 bit SQL Server. This turns off Lock pages in memory.
836 Causes SQL Server to size the buffer pool at startup based on the value of the max server memory option instead of based on the total physical memory. You can use trace flag 836 to reduce the number of buffer descriptors that are allocated at startup in 32-bit Address Windowing Extensions (AWE) mode.
Trace flag 836 applies only to 32-bit versions of SQL Server that have the AWE allocation enabled. You can turn on trace flag 836 only at startup.
845 SQL 9 & 10. For 64 bit SQL Server. This turns on Lock pages in memory.
1117 Grows all data files at once, else it goes in turns.
1118 Switches allocations in tempDB from 1pg at a time (for first 8 pages) to one extent. There is now a cache of temp tables. When a new temp table is created on a cold system it uses the same mechanism as for SQL 8. When it is dropped though, instead of all the pages being deallocated completely, one IAM page & one data page are left allocated, then the temp table is put into a special cache. Subsequent temp table creations will look in the cache to see if they can just grab a pre-created temp table. If so, this avoids accessing the allocation bitmaps completely. The temp table cache isn't huge (32 tables), but this can still lead to a big drop in latch contention in tempdb. http://www.sqlskills.com/BLOGS/PAUL/post/Misconceptions-around-TF-1118.aspx
1180 Forces allocation to use free pages for text or image data and maintain efficiency of storage. 1197 applies only in the case of SQL 7 – SP3. Helpful in case when DBCC SHRINKFILE and SHRINKDATABASE commands may not work because of sparsely populated text, ntext, or image columns
1197
1200 Prints lock information (the process ID and type of lock requested).
1202 Insert blocked lock requests into syslocks.
1204 Returns resources and types of locks participating in a deadlock and command affected. Scope: global only
1205 More detailed information about the command being executed at the time of a deadlock. This trace flag was documented in SQL Server 7.0 Books Online, but was not documented in SQL Server 8.
1206 Used to complement flag 1204 by displaying other locks held by deadlock parties
1211

Disables lock escalation based on memory pressure, or based on number of locks. The SQL Server Database Engine will not escalate row or page locks to table locks.

Using this trace flag can generate excessive numbers of locks. This can slow the performance of the Database Engine, or cause 1204 errors (unable to allocate lock resource) because of insufficient memory. For more information, see Lock Escalation (Database Engine).

If both trace flag 1211 and 1224 are set, 1211 takes precedence over 1224. However, because trace flag 1211 prevents escalation in every case, even under memory pressure, we recommend that you use 1224. This helps avoid "out-of-locks" errors when many locks are being used. Scope: global or session

1216

SQL 7 - Disables Health reporting. Lock monitor when detects a (worker thread) resource level blocking scenario. If a SPID that owns a lock is currently queued to the scheduler, because all the assigned worker threads have been created and all the assigned worker threads are in an un-resolvable wait state, the following error message is written to the SQL Server error log:

Error 1223: Process ID %d:%d cannot acquire lock "%s" on resource %s because a potential deadlock exists on Scheduler %d for the resource. Process ID %d:% d holds a lock "%h" on this resource.

1222 Returns the resources and types of locks that are participating in a deadlock and also the current command affected, in an XML format that does not comply with any XSD schema. Scope: global only
1224

Disables lock escalation based on the number of locks. However, memory pressure can still activate lock escalation. The Database Engine escalates row or page locks to table (or partition) locks if the amount of memory used by lock objects exceeds one of the following conditions:

·   40% of the memory that is used by Db Engine, exclusive of memory allocation using Address Windowing Extension (AWE). This is applicable when the locks parameter of sp_configure is set to 0.

·   Forty percent of the lock memory that is configured by using the locks parameter of sp_configure.

If both trace flag 1211 and 1224 are set, 1211 takes precedence over 1224. However, because trace flag 1211 prevents escalation in every case, even under memory pressure, we recommend that you use 1224. This helps avoid "out-of-locks" errors when many locks are being used.

Note:Lock escalation to the table- or HoBT-level granularity can also be controlled by using the LOCK_ESCALATION option of the ALTER TABLE statement.  Scope:global or session

1261

SQL 8 - Disables Health reporting. Lock monitor when detects a (worker thread) resource level blocking scenario. If a SPID that owns a lock is currently queued to the scheduler, because all the assigned worker threads have been created and all the assigned worker threads are in an un-resolvable wait state, the following error message is written to the SQL Server error log:

Error 1229: Process ID %d:%d owns resources that are blocking processes on scheduler %d.

1400 Enables the creation of the database mirroring endpoint, which is required for setting up and using database mirroring. This trace flag is allowed only when using the –T.
1462 Turns off log stream compression and effectively reverts the behavior back to ver 9.
1603 Use standard disk I/O (i.e. turn off asynchronous I/O).
1609 Turns on the unpacking and checking of remote procedure call (RPC) information in Open Data Services. Used only when applications depend on the old behavior.
1610 Boot the SQL dataserver with TCP_NODELAY enabled.
1611 If possible, pin shared memory -- check errorlog for success/failure.
1704 Prints information when a temporary table is created or dropped.
1717 Causes new objects being created to be system objects.
1806 Disables instant file initialization.
1807 Allows creating a database file on a mapped or UNC network location. unsupported under SQL Server 7 & 8.
2301 Enables advanced optimizations that are specific to decision support queries. This option applies to decision support processing of large data sets.
2330 Stops the collection of statistics for sys.db_index_usage_stats.
2382 Statistics collected for system tables.
2389 SQL 9 – Tracks the nature of columns by subsequent statistics updates. When SQL Server determines that the statistics increase three times, the column is branded ascending. The statistics will be updated automatically at query compile.
2390 Does the same like 2389 even if ascending nature of the column is not known and -- never enable without 2389.
2440 Parallel query execution strategy on partitioned tables. SQL 9 – uses a single thread per partition parallel query execution strategy. In ver. 10, multiple threads can be allocated to a single partition, thus improving the query’s response time.
2505 Prevents DBCC TRACEON 208, SPID 10 errors from appearing in the error log.
2508 Disables parallel non-clustered index checking for DBCC CHECKTABLE.
2509 Used with DBCC CHECKTABLE.html to see the total count of ghost records in a table
2520 Force DBCC HELP to return syntax of undocumented DBCC statements. If 2520 is not turned on, DBCC HELP will refuse to give you the syntax stating: "No help available for DBCC statement 'undocumented statement'".
2528

Disables parallel checking of objects by DBCC CHECKDB, CHECKFILEGROUP and CHECKTABLE. By default, the degree of parallelism is automatically determined by the query processor. The maximum degree of parallelism is configured just like that of parallel queries. For more information, see max degree of parallelism Option.

Parallel DBCC should typically be left enabled. For DBCC CHECKDB, the query processor reevaluates and automatically adjusts parallelism with each table or batch of tables checked. Sometimes, checking may start when the server is almost idle. An administrator who knows that the load will increase before checking is complete may want to manually decrease or disable parallelism.

Disabling parallel checking of DBCC can cause it to take much longer to complete and if DBCC is run with the TABLOCK feature enabled and parallelism set off, tables may be locked for longer periods of time.

Scope: global or session

2537 SQL 9 & 10. Allows function ::fn_dblog to look inside all logs (not just the active log).
2542 SQL 8 – Used with Sqldumper.exe to get certain dumps. In range 254x – 255x.
2551 Adds additional information to the dump file.
2701 Sets the @@ERROR system function to 50000 for RAISERROR messages with severity levels of 10 or less. When disabled, sets the @@ERROR system function to 0 for RAISERROR messages with severity levels of 10 or less.
2861 Cache query plans for queries that have a cost of zero or near to zero.
3001 Stops sending backup entries into MSDB.
3004 Gives out more detailed information about restore & backup activities.
3031 SQL 9 - will turn the NO_LOG and TRUNCATE_ONLY options into checkpoints in all recovery modes.
3104 Causes SQL Server to bypass checking for free space.
3111 Cause LogMgr::ValidateBackedupBlock to be skipped during backup and restore operations.
3205 If a tape drive supports hardware compression, either the DUMP or BACKUP statement uses it. With this trace flag, you can disable hardware compression for tape drivers. This is useful when you want to exchange tapes with other sites or tape drives that do not support compression. Scope: global or session
3213 Trace SQL Server activity during backup process so that we will come to know which part of backup process is taking more time.
3222 Disables the read ahead that is used by the recovery operation during roll forward operations.
3226 With this trace flag, you can suppress BACKUP COMPLETED log entries going to WIN and SQL logs.
3231 SQL 8 & 9 - will turn the NO_LOG and TRUNCATE_ONLY options into no-ops in FULL/BULK_LOGGED recovery mode, and will clear the log in SIMPLE recovery mode.
3282 SQL 6.5 – Used after backup restoration fails refer to microsoft for article Q215458.
3422 Cause auditing of transaction log records as they're read (during transaction rollback or log recovery). This is useful because there is no equivalent to page checksums for transaction log records and so no way to detect whether log records are being corrupted e careful with these trace flags - I don't recommend using them unless you are experiencing corruptions that you can't diagnose. Turning them on will cause a big CPU hit because of the extra auditing that's happening.
3502 Tracks CHECKPOINT - Prints a message to the log at the start and end of each checkpoint.
3503 Indicates whether the checkpoint at the end of automatic recovery was skipped for a database (this applies only to read-only databases).
3504 For internal testing. Will raise a bogus log-out-of-space condition from checkpoint()
3505 Disables automatic checkpoints. May increase recovery time and can prevent log space reuse until the next checkpoint is issued. Make sure to issue manual checkpoints on all read/write databases at appropriate time intervals.
Note does not prevent the internal checkpoints that are issued by certain commands, such as BACKUP.
3601 Stack trace when error raised. Also see 3603
3602 Records all error and warning messages sent to the client.
3603 SQL Server fails to install on tricore, Bypass SMT check is enabled, flags are added via registry. Also see 3601.
3604 Sends trace output to the client. This trace flag is used only when setting trace flags with DBCC TRACEON and DBCC TRACEOFF.
3605 Sends trace output to the error log.  (if SQL Server is started from CMD output also appears on the screen)
3607 Trace flag 3607 skips the recovery of databases on the startup of SQL Server and clears the TempDB. Setting this flag lets you get past certain crashes, but there is a chance that some data will be lost
3608 Prevents SQL Server from automatically starting and recovering any database except the master database. Databases will be started and recovered when accessed. Some features, such as snapshot isolation and read committed snapshot, might not work.
3609 Skips the creation of the tempdb database at startup. Use this trace flag if the device or devices on which tempdb resides are problematic or problems exist in the model database.
3610 SQL 9. Divide by zero to result in NULL instead of error.
3625 Limits the amount of information returned in error messages. For more information, see Metadata Visibility Configuration. Scope: global only
3626 Turns on tracking of the CPU data for the sysprocesses table.
3640 Eliminates the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. This is similar to the session setting of SET NOCOUNT ON, but when set as a trace flag, every client session is handled this way.
3689 Logs extended errors to errorlog when network disconnect occurs, turned off by default. Will dump out the socket error code this can sometimes give you a clue as to the root cause.
3913 SQL 7/8 – SQL Server does not update the rowcnt column of the sysindexes system table until the transaction is committed. When turned on the optimizer gets row count information from in-memory metadata that is saved to sysindexes system table when the transaction commits.
4013

This trace flag writes an entry to the SQL Server error log when a new connection is established. For each connection that occurs, the trace flag writes two entries that look like this:

Login: sa saSQL Query Analyzer(local)ODBCmaster, server process ID (SPID): 57, kernel process ID (KPID): 57.
Login: sa XANADUsaSQL Query Analyzer(local)ODBCmaster, server process ID (SPID): 57, kernel process ID (KPID): 57.

4022 If turns on, then automatically started procedures will be bypassed.
4029 Logs extended errors to errorlog when network disconnect occurs, turned off by default. Will dump out the socket error code this can sometimes give you a clue as to the root cause.
4030 Prints both a byte and ASCII representation of the receive buffer. Used when you want to see what queries a client is sending to SQL Server. You can use this trace flag if you experience a protection violation and want to determine which statement caused it. Typically, you can set this flag globally or use SQL Server Enterprise Manager. You can also use DBCC INPUTBUFFER.
4031 Prints both a byte and ASCII representation of the send buffers (what SQL Server sends back to the client). You can also use DBCC OUTPUTBUFFER.
4032 Traces the SQL commands coming in from the client. The output destination of the trace flag is controlled with the 3605/3604 trace flags.
4101

SQL 9 - Query that involves an outer join operation runs very slowly. However, if you use the FORCE ORDER query hint in the query, the query runs much faster. Additionally, the execution plan of the query contains the following text in theWarnings column:  NO JOIN PREDICATE

Turn these trace flags after HOTFIX is applied (SP2 CUP4)

4121
4606 Over comes SA password by startup. Refer to Ms article 936892.
4612 Disable the ring buffer logging - no new entries will be made into the ring buffer.
4613 Generate a minidump file whenever an entry is logged into the ring buffer.
4616 Makes server-level metadata visible to application roles. In SQL Server, an application role cannot access metadata outside its own database because application roles are not associated with a server-level principal. This is a change of behavior from earlier versions of SQL Server. Setting this global flag disables the new restrictions, and allows for application roles to access server-level metadata. Scope: global only
5302 Alters default behavior of select…INTO (and other processes) that lock system tables for the duration of the transaction. This trace flag disables such locking during an implicit transaction. 
6527

Disables generation of a memory dump on the first occurrence of an out-of-memory exception in CLR integration. By default, SQL Server generates a small memory dump on the first occurrence of an out-of-memory exception in the CLR. The behavior of the trace flag is as follows:

·   If this is used as a startup trace flag, a memory dump is never generated. However, a memory dump may be generated if other trace flags are used.

·   If this trace flag is enabled on a running server, a memory dump will not be automatically generated from that point on. However, if a memory dump has already been generated due to an out-of-memory exception in the CLR, this trace flag will have no effect. Scope: global only

7103 Disable table lock promotion for text columns. Refer to Ms article - 230044
7300 Retrieves extended information about any error you encounter when you execute a distributed query.
7501 Dynamic cursors are used by default on forward-only cursors. Dynamic cursors are faster than in earlier versions and no longer require unique indexes. This flag disables the dynamic cursor enhancements and reverts to version 6.0 behavior.
7502 Disables the caching of cursor plans for extended stored procedures.
7505 Enables version 6.x handling of return codes when calling dbcursorfetchex and the resulting cursor position follows the end of the cursor result set.
7525 Reverts to the SQL Server 7 behavior of closing nonstatic cursors regardless of the SET CURSOR_CLOSE_ON_COMMIT state in SQL Server 8.
7601 Turns on full text indexing. Together these four gather more information about full text search (indexing process) to the error log.
7603
7604
7605
7646 SQL 10. Avoids blocking when using full text indexing. An issue we experienced that full text can be slow when there is a high number of updates to the index and is caused by blocking on the docidfilter internal table.
7806 Enables a dedicated administrator connection (DAC) on SQL Svr Express. By default, no DAC resources are reserved on SQL Server Express.
8004 SQL server to create a mini dump once you enable 2551 and a out of memory condition is hit.
8011 Disables the collection of additional diagnostic information for Resource Monitor. You can use the information in this ring buffer to diagnose out-of-memory conditions. Scope: GLOBAL.
8012

Records an event in the schedule ring buffer every time that one of the following events occurs:

·   A scheduler switches context to another worker.

·   A worker is suspended or resumed.

·   A worker enters the preemptive mode or the non-preemptive mode.

You can use the diagnostic information in this ring buffer to analyze scheduling problems. For example, you can use the information in this ring buffer to troubleshoot problems when SQL Server stops responding.
Trace flag 8012 disables recording of events for schedulers. You can turn on trace flag 8012 only at startup.

8018 Disables the creation of the ring buffer, and no exception information is recorded. The exception ring buffer records the last 256 exceptions that are raised on a node. Each record contains some information about the error and contains a stack trace. A record is added to the ring buffer when an exception is raised.
8019 Disables stack collection during the record creation, has no effect if trace flag 8018 is turned on. Disabling the exception ring buffer makes it more difficult to diagnose problems that are related to internal server errors. You can turn on trace flag 8018 and trace flag 8019 only at startup.
8020 SQL Server uses the size of the working set when SQL Server interprets the global memory state signals from the operating system. Trace flag 8020 removes the size of the working set from consideration when SQL Server interprets the global memory state signals. If you use this trace flag incorrectly, heavy paging occurs, and the performance is poor. Therefore, contact Microsoft Support before you use. You can turn on trace flag 8020 only at startup
8033 SQL 9 – disable the reporting of CPU Drift errors in the SQL Server errorlog like time stamp counter of CPU on scheduler id 1 is not synchronized with other CPUs.
8202 Used to replicate UPDATE as DELETE/INSERT pair at the publisher. i.e. UPDATE commands at the publisher can be run as an "on-page DELETE/INSERT" or a "full DELETE/INSERT". If the UPDATE command is run as an "on-page DELETE/INSERT," the Logreader send UDPATE command to the subscriber, If the UPDATE command is run as a "full DELETE/INSERT," the Logreader send UPDATE as DELETE/INSERT Pair. If you turn on trace flag 8202, then UPDATE commands at the publisher will be always send to the subscriber as DELETE/INSERT pair.
8206 Supports stored procedure execution with a user specified owner name for SQL Server subscribers or without owner qualification for heterogeneous subscribers in SQL Server 8.
8207 Enables singleton updates for Transactional Replication, released with SQL Server 8 SP 1.
8501 Writes detailed information about Ms-DTC context & state changes to the log.
8599 Allows you to use a savepoint within a distributed transaction.
8602 Ignore index hints that are specified in query/procedure.
8679 Prevents the SQL Server optimizer from using a Hash Match Team operator.
8687 Used to disable query parallelism.
8721 Dumps information into the error log when AutoStat has been run.
8722 Disable all other types of hints. This includes the OPTION clause.
8744 Disables pre-fetching for the Nested Loops operator. Incorrect use of this trace flag may cause additional physical reads when SQL Server executes plans that contain the Nested Loops operator. For more information about the Nested Loops operator, see the "Logical and physical operators reference" topic in SQL Server 9 BOL.
You can turn on trace flag 8744 at startup or in a user session. When you turn on trace flag 8744 at startup, the trace flag has global scope. When you turn on trace flag 8744 in a user session, the trace flag has session scope.
8755 Disable any locking hints like READONLY. By setting this, you allow SQL Server to dynamically select the best locking hint for the query.
8783 Allows DELETE, INSERT, and UPDATE statements to honor the SET ROWCOUNT ON setting when enabled.
8816 Logs every two-digit year conversion to a four-digit year.
9134 SQL 8 – Does additional reads to test if the page is allocated & linked correctly this checks IAM & PFS. Fixes error 601 for queries under Isolation level read uncommitted.
9268

SQL 8 – When SQL Server runs a parameterized query that contains several IN clauses, each with a large number of values, SQL Server may return the following error message after a minute or more of high CPU utilization:

Server: Msg 8623, Level 16, State 1
Internal Query Processor Error: The query processor could not produce a query plan. Contact your primary support provider for more information.

http://support.microsoft.com/kb/325658 Enabling this trace flag activates the hotfix.


http://msdn.microsoft.com/en-us/library/ms188396.aspx

Posted by 보미아빠


미리읽기란? 

I/O 와 CPU 연산을 동시에 수행해 그 수행 성능을 최대로 만들어 보겠다 라는 최적화 알고리즘이다.
상식적으로 읽고 연산 해야 하지만, "미리 쓰일것 같아, 먼저 읽어 두겠다." 는 것이고, 그로 인해 연산을 먼저 시작할 수 있으므로 성능은 더 낳아진다. 라는 이론이다. 하지만 side effect 로 영원히 읽지 않아도 되는 것을 미리 읽어 I/O 성능을 갉아 먹을 수 있는 역 기능을 수행 할 수도 있다.

미리읽기는 IAM 을 이용하는 방법과 index 의 non-leaf 를 이용하는 방법이 있다. 이것의 작동 방식은 BOL에 상세히 나와 있다. 조금만 살펴 본다면, IAM 이 bit 단위로 extents 할당 단위를 표현하고 있고, 이 IAM 1Byte를 읽어 (8 extents = 64K * 8 = 512K) 씩 물리적 방향에 맞게 ASync 방식으로 읽을수 있다. 또 Index 의 경우,  index 의 non-leaf 를 읽어 모여있는 페이지를 몇개를 Async 로 순서에 맞게 읽을 수 있으므로, 그 성능을 좋게 할 수 있다. 핵심은 역시 I/O 와 CPU 연산을 동시에 할 수 있다는 것이 가장 크다. SQL Server EE 의 경우 미리 읽기를 더 잘 할 수 있다.

 


 

2008 R2

http://msdn.microsoft.com/en-us/library/ms191475(v=sql.105).aspx

The read-ahead mechanism allows the Database Engine to read up to 64 contiguous pages (512KB) from one file.

 

 

2000

http://technet.microsoft.com/en-us/library/cc966500.aspx

SQL Server uses the Win32 API calls as follows.

 

 

API

Common Usage

CreateFile

Used to create and open database and log files. The flags FILE_FLAG_OVERLAPPED, FILE_FLAG_WRITETHROUGH, and FILE_FLAG_NO_BUFFERING are specified to avoid nonstable media caching.

WriteFile

Primarily used by the log manager and backup manager to handle I/Os.

ReadFile

Primarily used by the log manager and backup manager to handle I/Os.

WriteFileGather

Primarily used by the buffer pool to write page groups (up to sixteen 8-KB pages in a group).

ReadFileScatter

Primarily used by the buffer pool to read pages into the buffer pool. Can be used for single page requests as well as read-ahead requests. Read-ahead requests are generally 128 pages for each group but can be as many as 1,024 pages when running Microsoft SQL Server Enterprise Edition.

HasOverlappedIoCompleted

Used to determine the status of I/O requests.

GetOverlappedResults

Used to determine success of the I/O requests.

 

 

디버깅 하니....다 나오는구만....-_- 궁금해 할 필요 없이 보면 된다....!

 


미리 읽기의 비 활성화 방법

관련 TRACE FLAG
652 Disables read ahead for the server.
653 Disables read ahead for the current connection.
3222 Disables the read ahead that is used by the recovery operation during roll forward operations.

BOL
http://msdn.microsoft.com/ko-kr/library/ms191475.aspx

좋은 아티클 테스트 포함

http://sqlblog.com/blogs/linchi_shea/archive/2008/07/04/performance-impact-some-data-points-on-read-ahead.aspx
http://technet.microsoft.com/en-us/library/cc966500.aspx
http://technet.microsoft.com/en-us/library/cc917726.aspx

위 아티클을 읽으면, 읽기의 물리적인 단위는 extents 이고 논리적인 읽기의 단위는 page 이다. 쓰기의 물리적인 단위는 page 이다. 그리고, 823,824 등등 오류의 정의도 볼 수 있다.

Object ID

This is the ID of the object to which the page is assigned within the schema of the database. A page can be assigned to only a single object. When the page is read from disk, the object ID is checked on the page. If the object ID does not match the expected object ID, SQL Server will generate Error 605.

SQL Server often performs its writes on page-sized, 8-KB, or larger boundaries.

Extents

SQL Server generally (except for nonmixed extents) allocates space an extent at a time. An extent is eight 8-KB pages, or 64 KB. SQL Server often performs reads in extent-sized (64 KB or 128 KB) boundaries as well.

Read-Ahead

SQL Server 2000 uses ReadFileScatter to perform read-ahead operations. SQL Server uses sophisticated algorithms to retrieve data pages that are going to be used in the immediate future.

For example, if you run a query that can use an index to determine applicable rows, a read-ahead may occur on the actual data pages that are needed to complete the select list. As index entries are identified, SQL Server can post OVERLAPPED (async) I/O operations for the data pages that will be used in upcoming steps of the query plan. This is how a query using a bookmark lookup operator uses read-ahead.

This example is just one of many read-ahead situations that SQL Server can use. Allowing the index searching to continue while the data page I/O is in progress maximizes the CPU and I/O of the system. The I/O is often completed by the time it is needed so other steps in the plan have direct memory access to the needed data and do not have to stall while waiting on I/O.

When a read-ahead is posted, it can be from 1 to 1,024 pages. SQL Server limits a single read-ahead request depth to 128 pages on most editions. However, Microsoft SQL Server Enterprise Edition raises the limit to 1,024 pages.

SQL Server uses the following steps to set up read-ahead.

  1. Obtain the requested amount of buffers from the free list.

  2. For each page:

    1. Determine the in-memory status of the page by doing a hash search.

    2. If found to be already in memory, set up the read-ahead request to immediately return the buffer to the free list upon I/O completion.

    3. Establish the proper I/O request information for ReadFileScatter invocation.

    4. Acquire I/O latch to protect buffer from further access.

    5. If the page is not found in hash search then insert it into the hash table.

  3. Issue the ReadFileScatter operation to read the data.

When the I/O operation is complete, each page is sanity checked for a valid page number and torn page errors. In addition, various other data integrity and safety checks are performed. The I/O latch is then released so the page is available for use if it is located on the hash chain. If the page was determined to be already in memory, the page is immediately discarded to the free list.

This process shows the key factors of SQL Server I/O patterns. Read-ahead goes after pages that can already be in memory or not allocated. Because SQL Server maintains the in-memory buffers and hash chains, SQL Server tracks the page’s state. Importantly, read-ahead processing opens the door for overlapping read and write requests at the hardware level.

If a page is already in memory when the read-ahead request is posted, the contiguous read is still needed and is faster than breaking up read requests into multiple physical requests. SQL Server considers the read to be unusable for the page in question, but many of the pages around it may be usable. However, if a write operation is in progress when the read is posted, the subsystem has to determine which image of the read to return. Some implementations return the current version of the page before the write is complete; others make the read wait until the write completes; and yet others return a combination, showing partially new data and partially old data. The key is that SQL Server will discard the read as unusable but the subsystem needs to maintain the proper image for subsequent read operations. The in-progress write, when completed, must be the next read image returned to the server running SQL Server.

Do not confuse read-ahead with parallel query plans. Read-ahead occurs independently of the parallel query plan selection. The parallel plan may drive I/O harder because multiple workers are driving the load, but read-ahead occurs for serial and parallel plans. To ensure that parallel workers do not work on the same data sets, SQL Server implements the parallel page supplier to help segment the data requests.

Reads
When a page or log block is read from disk, the checksum (page audit) value is calculated and compared to the checksum value that was stored on the page or log block. If the values do not match, the data is considered to be damaged and an error message is generated.

SQL Server uses read-ahead logic to avoid query stalls caused by I/O waits. The read-ahead design tries to keep the physical reads and checksum comparisons out of the critical path of the active query, decreasing the performance effects of checksum activity.

    Read-ahead enhanced

In SQL Server 2005, the read-ahead design is enhanced so that it reduces physical data transfer requirements by trimming the leading and trailing pages from the request if the data page(s) are already in the buffer pool.

For more information on SQL Server read-ahead logic, see SQL Server I/O Basics (http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/sqlIObasics.mspx).

For example, a read-ahead request is to be issued for pages 1 through 128 but pages 1 and 128 are already located in the SQL Server buffer pool. The read-ahead request would be for pages 2 through 127 in SQL Server 2005. In comparison, SQL Server 2000 requests pages 1 through 128 and ignores the data that is returned for pages 1 and 128.

Posted by 보미아빠

최근에 달린 댓글

최근에 받은 트랙백

글 보관함