'분류 전체보기'에 해당되는 글 192건
- 2011.10.20 Window 서비스 등록/삭제 방법
- 2011.10.19 MongoDB 알아볼까? 1
- 2011.10.13 최소로그 Flag -T610
- 2011.10.10 Hash Join 제약.
- 2011.10.10 Join의 종류 1
- 2011.10.05 Admin::2000용 TEST DB 생성.
- 2011.10.05 T-SQL::테이블 확장속성
- 2011.10.03 T-SQL::create assembly
- 2011.08.14 SQLCLR Disk 사이즈 확인
- 2011.08.14 Admin:: SQL Server 에러로 다른 서버에서 Rebuilding 처리
- 2011.08.14 SQL2012::설치
- 2011.08.13 T-SQL:: TCP 포트 정보
- 2011.08.13 T-SQL:: INDEX-중복인덱스 제거. 1
- 2011.04.15 T-SQL:: Default Trace로 DB 증가량 확인 1
- 2011.03.30 Admin::Cache Flush 가 발생하는 경우
윈도위 서비스 등록 삭제 방법.
1. 서비스 등록
sc create “New Service” binPath= “C:\TestFolder\TestApp.exe”
New Server = 서비스 이름
2. 서비스 삭제
'ETC' 카테고리의 다른 글
메모리 dump 분석 예 ( 정확하지 않음 ) (0) | 2014.11.06 |
---|---|
Windbg 명령어 & 설치 (0) | 2014.11.06 |
Admin::Superdome VS DL580 G7 (0) | 2011.01.10 |
믹시 가입 (0) | 2010.10.13 |
'Mongo DB' 카테고리의 다른 글
MongoDB 설치 - Windows (2) | 2011.10.20 |
---|
성능이슈인 2가지를 생각해야 한다.
쓰기가 두번 이루어지고, rollback을 위한 Log Space Reservation이 크다.
참고) http://blogs.msdn.com/b/sqlserverstorageengine/archive/2008/10/24/new-update-on-minimal-logging-for-sql-server-2008.aspx
-- create the source table. This table stores 2 row per page
create table t_source (c1 int, c2 int, c3 char (3000))
go
-- I insert 10000 rows. With 2 rows/page, I will have 5000 pages so
-- the size of the table is 40MB
declare @i int
select @i = 1
while (@i < 10000)
begin
insert into t_source values (@i, @i+10000, 'hello')
select @i= @i + 1
end
-- create target table with clusttered index
create table t_ci (c1 int, c2 int, C3 CHAR(3000))
go
create clustered index ci on t_ci(c1)
go
-- I will now insert all the rows from the source table into the target
-- table and measure (a) logspace used (b)logspace reserved (c) number of writes
-- both with TF-610 ON and OFF.
-- Here is the INSERT statement
begin tran
insert into t_ci select * from t_source order by c1
rollback
|
# of page writes(appx) | Logspace used (appx) | Logspace reserved (appx) |
TF-610 OFF | 5000 | 34MB | 8MB |
TF-610 ON | 10000 | 3.5MB | 82MB |
'Trace Flag' 카테고리의 다른 글
Admin::SQL Server Trace Flags (0) | 2010.06.07 |
---|---|
Trace Flag (0) | 2010.06.04 |
Admin::TF 1118 사용 이유 (0) | 2009.11.04 |
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
,c1 int
)
go
create table tbly
(idx int
,c1 int
)
go
insert into tblx values (1,1)
insert into tblx values (1,2)
insert into tbly values (1,1)
insert into tbly values (2,null)
go
select * from tblx
select * from tbly
set statistics profile on
select *
from tblx a
join tbly b
on a.idx = b.idx
where a.idx > 1
option (hash join)
select *
from tblx a
join tbly b
on a.idx = b.idx
where a.idx = 1
option (hash join)
메시지8622, 수준16, 상태1, 줄1
이쿼리에정의된힌트로인해쿼리프로세서에서쿼리계획을생성할수없습니다. 힌트를지정하거나SET FORCEPLAN을사용하지않고쿼리를다시전송하십시오.
-
select *
from tblx a
join tbly b
on a.idx = b.idx
where a.idx = 1
- Hash Join은 적어도 하나의 equijoin predicate가 있어야 풀 수 있다. 그런데 위 커리는 그런 부분이 없다. Mearge join도 마찬가지다.
select *
from tblx a
full outer join tbly b
on a.idx = 1
option (merge join)
- 위 쿼리는 가능하다. Full outer mearge join의 경우 non equijion도 가능하기 때문이다.
select *
from tblx a
join tbly b
on a.idx > b.idx
- Hash join이 가능한가? 안된다. Hash 함수는 통과한 값의 크다 작다를 비교할 수 없다.
-
select *
from tblx a
join tbly b
on a.idx > b.idx
option (hash join)
메시지 8622, 수준 16, 상태 1, 줄 1
이 쿼리에 정의된 힌트로 인해 쿼리 프로세서에서 쿼리 계획을 생성할 수 없습니다. 힌트를 지정하거나 SET FORCEPLAN을 사용하지 않고 쿼리를 다시 전송하십시오.
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
,c1 int
)
go
create table tbly
(idx int
,c1 int
)
go
insert into tblx values (1,1)
insert into tblx values (2,2)
insert into tbly values (1,1)
insert into tbly values (2,null)
go
select * from tblx where c1 in (select c1 from tbly) option(hash join)
select * from tblx where c1 not in (select c1 from tbly) option(hash join)
에러. null 있다.
- Tblx에 c1 컬럼에 not null 체크조건을 주거나 null을 입력하지 않으면 hash join을 잘 사용할 수 있다.
혹은 아래 처럼 한다. 그래야 equijoin predicate 가 존재한다.
select * from tblx where c1 not in (select c1 from tbly where c1 is not null)
and c1 is not null option(hash join)
'Peformance Tuning' 카테고리의 다른 글
query plan의 실행 옵션 보기 (0) | 2012.01.29 |
---|---|
Dynamic Management Views (0) | 2012.01.22 |
Join의 종류 (1) | 2011.10.10 |
Tuning::Top 10 SQL Server performance Tuning (0) | 2011.01.16 |
1) 조인의 종류 : 물리적인 방법의 조인을 말한다.
A. 중첩 루프 (Nested Lopp) 조인
B. 병합 (Merge) 조인
C. 해시 (Hash) 조인
D. Remote 조인
- Row 많아질수록 쿼리의 Cost가 높아진다, Loop가 가장 기본 적인 방법이며, 양이 적을때에는 성능이 좋지만 데이터가 많아질수록 비용도 급격히 증가한다.
- Merge 방식은 데이터가 적을 경우에는 Loop 보다는 못하지만, 양이 많아 질수록 더 뛰어난 성능을 보인다.
- Hash 방식은 데이터가 얼마 없을 경우에는 Overhead로 인하여 성능이 좋지 않지만 데이터가 많을수록 Loop 보다는 낮고 Merge 보다는 못하게 비용이 증가한다.
1) Nested Loop (중첩 루프 조인)
- 한집합의 원소값을 다른 집합의 원소 값과 매칭해 나가는 작업, 가능한 모든 경우를 조회하여 결과 집합을 찾는 방법
- 선행테이블 (Drving Table ) = 바깥 테이블 = 찾는 주체가 되는 테이블
- 후행 테이블 (Driven Table) = 안쪽 테이블 = 비교 대상이 되는 테이블
- 여기서 바깥/안쪽 의 의미는 조인에서의 위치가 아닌 먼저 조회 되느냐 마느냐의 의미임.
- 힌트가 없을시에는 선행테이블은 옵티마이저가 알아서 배치하나 힌트가 있을 시에는 테이블 배치 순서에 따른다.
- 성능을 높이기 위한 방법
n 후행 테이블의 크기가 작을수록, 후해 테이블에 인덱스가 미리 설정되어야 한다.
n 선행 테이블이 이미 sort되어 있으면 좀 더 빠르다.
- set statistics io on
-
- select e.emp_id, e.fname + e.lname as name, j.job_id, j.job_desc
- from dbo.employee as e with(nolock)
- join jobs as j with(nolock) on e.job_id = j.job_id
- 테이블 'jobs'. 검색 수 43, 논리적 읽기 수 86,
- 테이블 'employee'. 검색 수 1, 논리적 읽기 수 2,
- 실행계획에 employee 부터 읽혀지며, job_id에 인덱스가 없기 때문에 full scan 하는것과 동일하다. 아래 그림처럼 emplolyee의 job_id를 읽어서 순서대로 jobs테이블에 찾는 작업을 한다.
- Employee 테이블의 row수가 43개 행이기 때문에 jobs을 43번 scan 한다.
그럼 강제로 jobs를 선행 테이블로 읽게 변경해 보자.
- select e.emp_id, e.fname + e.lname as name, j.job_id, j.job_desc
- from jobs as j with(nolock)
- join employee as e with(nolock) on e.job_id = j.job_id
- option (force order, loop join)
-
- --테이블'employee'. 검색수14, 논리적읽기수29
- --테이블'jobs'. 검색수1, 논리적읽기수2
- Cost 비용을 봐서는 jobs늘 선행 테이블로 해서 강제로 loop 하는것이 더 좋아보인다.
- Jobs 테이블의 row 수만큼 employee 를 풀 스캔 한다. (14개)
- 아래 쿼리는 두 테이블의 데이터 길이이다.
- select CAST( sum( datalength(emp_id) + datalength(fname) + datalength(minit)
- + datalength(lname) + datalength(job_id) + datalength (job_lvl) + DATALENGTH(pub_id)
- + DATALENGTH(hire_date)) as varchar) + ' byte'
- from employee with(nolock)
- --1607 byte
-
- select CAST( sum( datalength(job_id) + datalength(job_desc) + datalength(min_lvl)
- + datalength(max_lvl) ) as varchar) + ' byte'
- from JOBS with(nolock)
- --314 byte
- 첫번째 쿼리는 employee 테이블 만큼 스캔 하였으니 1067 바이트 만틈 읽었고 jobs는 clustred index seek 하였으니 314 바이트 만큼 읽었다. 총 1067+ 314 = 1921 byte
- 두번째 쿼리는 jobs를 먼저 full scan 하였으므로 (1067 * 14) + 314 = 22812 byte
- 첫번째 쿼리가 11배 정도 입/출력이 작다. 쿼리의 성능을 입/출력 양으로 측정은 쿼리 수행 속도를 결정한다., 위 두 쿼리는 어떤 테이블을 사용하던지 한쪽은 full scan 해야 한다.
create index IDX_EMPLOYEE_JOB_ID on employee ( job_id)
- 인덱스를 생성하고 두번째 쿼리를 다시 실행하면 employee 를 index seek 하기 때문에 좀 더 성능이 좋아진다.
- 일반적으로 테이블의 10% 정도까지의 데이터를 접근할 때 인덱스를 사용하는 것이 낮다고 한다 실제적으로 쿼리 수행해보면 (8% 정도 였던것 같기도 함) 그러나 이것도 상대적이다 1억건의 테이블에서 1천만건을 읽는데 인덱스 이용하면 오래 걸린다. 인덱스로 한건 한건 접근하기 때문이다.
- 인덱스를 사용하지 않고 조인 한다면
- select e.emp_id, e.fname + e.lname as name, j.job_id, j.job_desc
- from jobs as j with(index(0))
- join employee as e with(index(0)) on e.job_id = j.job_id
- 테이블 'employee'. 검색 수 1, 논리적 읽기 수 2
- 테이블 'jobs'. 검색 수 1, 논리적 읽기 수 2,
- Hash 조인을 사용한다. Merge join의 경우 sort를 하기 때문에 비용이 더 많이 든다. 이 두 테이블은 row수가 많이 않기 때문에 hash join이 가장 적합하다.
2) Mearge Join (병합조인)
- 전제 조건은 양 테이블이 모두 조인 키에 의해 정렬되어 있어야 함.
- 선행,후행 테이블의 크기는 성능과 관련이 없다, 그러나 선행 테이블이 중복 행이 존재하지 않을 때, 즉 고유할 때, 메모리 사용량이 적으며, 이것이 권장된다.
- 병합조인은 중복 행이 존재한다면 어지간히 해서 발생하지 않는다, 그래서 다:1 관계에서 발생하지 다:다 에서는 발생하지 않는다. 이럴 경우는 hash join을 한다.
- 큰 장점은 양쪽 테이블에서 스캔 수가 한번 일어난다.
- 데이터가 많을 때 이미 정렬되어 있기 때문에 전부 찾지 않는다.
- 정렬되어 있지 않다면 정렬 하는 작업을 하기 때문에 메모리를 더 사용할 수 있다. 그래서 유니클 할때만 힌트를 사용해서 고정하는 것이 좋다. 그렇지 않으면 정렬 비용이 발생하고 tempdb의 페이지 할당이 증가된다.
- select *
- from employee as e
- join jobs as j on e.job_id = j.job_id
- option(merge join)
테이블'jobs'. 검색수1, 논리적읽기수2
테이블'employee'. 검색수1, 논리적읽기수88
3) Hash Join
- 선행 테이블을 해시 버킷을 만드는데 사용되며, 이것을 빌드 입력이라고 부른다. 후행 테이블은 검색입력 이라고 부른다.
- 선행 테이블은 후행 테이블이 처리되기 전에 완전히 읽혀져야 함으로 응답 시간이 조인들 중에서 가장 늦다.
- 작은 테이블이 선행 테이블로 사용되어져야 한다. 큰 테이블이 선행 테이블이 되면 해시 버킷을 만들어야 하는데 메모리 사용량이 늘어 난다.
- 해시조인의 결과의 순서가 없다 그래서 순서가 필요하다면, ORDER BY를 꼭 명시해야 한다.
- 인덱스가 없을 때 주로 해시 조인이 사용된다.
- select *
- from employee as e
- join jobs as j on e.job_id = j.job_id
- option(hash join)
- 테이블 'employee'. 검색 수 1, 논리적 읽기 수 2
- 테이블 'jobs'. 검색 수 1, 논리적 읽기 수 2,
1) Input Order 필요한가?
요즘 옵티마이저는 똑똑해서 필요 없다.
- Loop join : 아니다, 하지만 더 낳은 성능을 위해 선행 테이블이 정렬될 수도 있다.
- Merge join : 양 테이블이 반드시 조인 키에 의해 정렬되어 있어야 한다.
- Hash join : 필요 없다.
2) Sort Order 필요한가?
- Loop join : 선행 테이블
- Merge join : 둘 다
- Hash join : 필요 없다.
3) 선행/후행 테이블 선택은 어떻게 ?
- Loop join : 후행 테이블은 인덱스가 있거나 작아야 한다.
- Merge join : 별로 중요하지 않다.
- Hash join : 작은 테이블이 선행 테이블이 되어야 한다.
4) 메모리 사용량
- Loop join : 추가 메모리 필요 없다.
- Merge join : back loop 위해 추가 메모리 필요
- Hash join : 해시 버킷을 위해 추가 메모리 필요
'Peformance Tuning' 카테고리의 다른 글
Dynamic Management Views (0) | 2012.01.22 |
---|---|
Hash Join 제약. (0) | 2011.10.10 |
Tuning::Top 10 SQL Server performance Tuning (0) | 2011.01.16 |
SQL Server Best Practices Article (0) | 2011.01.16 |
http://www.microsoft.com/download/en/confirmation.aspx?id=23654
해당 파일을 받아서 스크립트 실행해 주면 됩니다.
'Common Admin' 카테고리의 다른 글
SQL Server tempdb 복구 (0) | 2013.01.08 |
---|---|
tablediff 유틸리티 (0) | 2012.11.01 |
Admin:: SQL Server 에러로 다른 서버에서 Rebuilding 처리 (0) | 2011.08.14 |
Admin::Cache Flush 가 발생하는 경우 (0) | 2011.03.30 |
테이블 확장 속성 확인 쿼리
-- 테이블에 대한 속성 SELECT object_name(major_id) as table_name, value FROM sys.extended_properties WHERE minor_id = 0 ORDER BY major_id -- 컬럼 확장 속성 declare @tb_nm sysname set @tb_nm = 'SF_COMMENT' SELECT object_name(major_id) as table_name, c.name ,value FROM sys.extended_properties as p with(nolock) inner join sys.columns as c with(nolock) on p.major_id = c.object_id and p.minor_id = c.column_id WHERE p.class = 1 and p.minor_id != 0 and p.major_id = OBJECT_ID(@tb_nm) order by p.major_id, p.minor_id SELECT * FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table', @tb_nm, 'column', default)
'T-SQL' 카테고리의 다른 글
T-SQL:: 인덱스 압축 예상 Size (0) | 2012.07.26 |
---|---|
TSQL::월별 누적 건수를 구하기. (0) | 2012.01.29 |
T-SQL::create assembly (0) | 2011.10.03 |
SQLCLR Disk 사이즈 확인 (0) | 2011.08.14 |
CREATE ASSEMBLY assembly_name [ AUTHORIZATION owner_name ] FROM { <client_assembly_specifier> | <assembly_bits> [ ,...n ] } [ WITH PERMISSION_SET = { SAFE | EXTERNAL_ACCESS | UNSAFE } ] [ ; ] <client_assembly_specifier> :: ='[\\computer_name\]share_name\[path\]manifest_file_name' | '[local_path\]manifest_file_name'<assembly_bits> :: = { varbinary_literal | varbinary_expression }
SQL Server에서 어셈블리에 액세스할 때 이 어셈블리에 부여된 코드 액세스 권한 집합을 지정합니다. 지정하지 않으면 기본적으로 SAFE가 적용됩니다.
SAFE를 사용하는 것이 좋습니다. SAFE는 가장 제한적인 권한 집합입니다. SAFE 권한을 사용하여 어셈블리에서 실행한 코드는 파일, 네트워크, 환경 변수 또는 레지스트리와 같은 외부 시스템 리소스에 액세스할 수 없습니다.
EXTERNAL_ACCESS를 사용하면 어셈블리에서 파일, 네트워크, 환경 변수 및 레지스트리와 같은 특정 외부 시스템 리소스에 액세스할 수 있습니다.
UNSAFE를 사용하면 어셈블리에서 SQL Server 인스턴스의 내부 리소스와 외부 리소스 모두에 제한 없이 액세스할 수 있습니다. UNSAFE 어셈블리 내에서 실행되는 코드는 비관리 코드를 호출할 수 있습니다.
SAFE 권한 설정은 SQL Server 인스턴스의 외부 리소스에 액세스하지 않고 계산 및 데이터 관리 태스크를 수행하는 어셈블리에 권장됩니다.
SQL Server 인스턴스의 외부 리소스에 액세스하는 어셈블리에는 EXTERNAL_ACCESS를 사용하는 것이 좋습니다. EXTERNAL_ACCESS 어셈블리는 SAFE 어셈블리 수준의 안정성 및 확장성 보호를 제공하지만 보안 측면에서는 UNSAFE 어셈블리와 유사합니다. 그 이유는 EXTERNAL_ACCESS 어셈블리의 코드에서 명시적으로 호출자를 가장하지 않는 한 기본적으로 코드가 SQL Server 서비스 계정으로 실행되고 이 계정을 통해 외부 리소스에 액세스하기 때문입니다. 따라서 EXTERNAL_ACCESS 어셈블리를 만드는 사용 권한은 SQL Server 서비스 계정에서 코드를 실행하도록 트러스트된 로그인에만 부여해야 합니다. 가장에 대한 자세한 내용은 CLR 통합 보안를 참조하십시오.
UNSAFE를 지정하면 어셈블리의 코드를 사용하여 SQL Server 프로세스 공간에서 모든 작업을 자유롭게 수행할 수 있게 되므로 SQL Server가 취약해질 가능성이 있습니다. UNSAFE 어셈블리는 SQL Server 또는 공용 언어 런타임 중 하나의 보안 시스템을 손상시킬 수도 있습니다. 따라서 UNSAFE 권한은 가장 높은 수준의 트러스트된 어셈블리에만 부여해야 합니다. sysadmin 고정 서버 역할의 멤버만 UNSAFE 어셈블리를 만들고 변경할 수 있습니다.
'T-SQL' 카테고리의 다른 글
TSQL::월별 누적 건수를 구하기. (0) | 2012.01.29 |
---|---|
T-SQL::테이블 확장속성 (0) | 2011.10.05 |
SQLCLR Disk 사이즈 확인 (0) | 2011.08.14 |
T-SQL:: TCP 포트 정보 (0) | 2011.08.13 |
'T-SQL' 카테고리의 다른 글
T-SQL::테이블 확장속성 (0) | 2011.10.05 |
---|---|
T-SQL::create assembly (0) | 2011.10.03 |
T-SQL:: TCP 포트 정보 (0) | 2011.08.13 |
T-SQL:: INDEX-중복인덱스 제거. (1) | 2011.08.13 |
'Common Admin' 카테고리의 다른 글
tablediff 유틸리티 (0) | 2012.11.01 |
---|---|
Admin::2000용 TEST DB 생성. (0) | 2011.10.05 |
Admin::Cache Flush 가 발생하는 경우 (0) | 2011.03.30 |
Admin::Configuring Windows 2003 ( x64 ) for SQL Server (0) | 2010.12.28 |
현재는 RC버전
- 설치 방법
http://sqlblog.com/blogs/aaron_bertrand/archive/2011/07/12/sql-server-v-next-denali-ctp3-installation-walk-through.aspx
- 다운 로드
https://www.microsoft.com/betaexperience/pd/SQLDCTP3CTA/enus/default.aspx
팀 블로그
http://blogs.technet.com/b/dataplatforminsider/archive/2011/08/10/sql-server-code-name-denali-ctp3-product-guide-is-here.aspx
SQL Server 개발툴(Juneau)
http://blogs.msdn.com/b/dave_langer/archive/2011/07/13/sql-server-developer-tools-codename-juneau-available-now.aspx
--SQL 2000/2005 Version set nocount on go DECLARE @SqlPort Nvarchar(10) DECLARE @instance_name Nvarchar(30) DECLARE @reg_key Nvarchar(500) Declare @value_name Nvarchar(20) if left(CAST(SERVERPROPERTY('ProductVersion')AS sysname),1) = '9' BEGIN select @instance_name = CAST(SERVERPROPERTY('instancename')AS sysname) if @instance_name is NULL BEGIN set @reg_key = 'SOFTWARE\Microsoft\MSSQLServer\MSSQlServer\SuperSocketNetLib\Tcp' END ELSE BEGIN set @reg_key = 'SOFTWARE\Microsoft\Microsoft SQL Server\' + @instance_name + '\MSSQLServer\SuperSocketNetLib\Tcp' END EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@reg_key, @value_name='TcpPort', @value=@SqlPort output select CAST(SERVERPROPERTY('ServerName')AS sysname) as ServerName, @SqlPort as Port END if left(CAST(SERVERPROPERTY('ProductVersion')AS sysname),1) = '8' BEGIN Create table #Port_2000 (value nvarchar(20),Data nVarchar(10)) insert into #Port_2000 exec master..xp_instance_regread 'HKEY_LOCAL_MACHINE', 'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\Supersocketnetlib\tcp', 'tcpPort' select @SqlPort = Data from #Port_2000 select CAST(SERVERPROPERTY('ServerName')AS sysname) as ServerName, @SqlPort as Port drop table #Port_2000 END
'T-SQL' 카테고리의 다른 글
T-SQL::create assembly (0) | 2011.10.03 |
---|---|
SQLCLR Disk 사이즈 확인 (0) | 2011.08.14 |
T-SQL:: INDEX-중복인덱스 제거. (1) | 2011.08.13 |
DBCC ShrinkFile (0) | 2010.09.06 |
/* Find Duplicate Indexes This script returns the Duplicate indexes on any database I use 2 User defined Functions Compatible with SQLServer 2000 (I used sp3) It won't work in SQL Server 7.0 because It uses user-defined functions and a Memory. Created by G.R. Preethiviraj Kulasingham pkulasingham@virtusa.com Written on : February 20, 2003 Modified on : May 18, 2004 Additional code written to remove duplicate entries. Additional code to include index properties. */ IF EXISTS(Select id from sysobjects Where id = object_id('dbo.GetColID')) DROP FUNCTION dbo.getColID GO Create Function dbo.getColID (@TableID int, @indid int) /* Parameters: @TableID: ID of the Table @IndID : ID of the Index Returns All the Columns (ID) for the given index in string format seperated by '&'sign. '-' is added for descending keys */ Returns Varchar(200) As BEGIN Declare @SQL varchar(200) Set @SQL ='' Select @SQL= @SQL +'&'+ convert(varchar(7),((indexkey_property(id, indid, keyno, 'isdescending')*-2)+1)* colid) from sysindexkeys Where id =@Tableid and indid=@Indid Order by id, indid, Keyno IF LEN(@SQL)>1 Select @SQL = @SQL +'&' Return @SQL END GO IF EXISTS(Select id from sysobjects Where id = object_id('dbo.GetColList')) DROP FUNCTION dbo.getColList GO Create Function dbo.getColList (@Tableid int, @indid int) /* Parameters: @TableID: ID of the Table @IndID : ID of the Index Returns Index Key (column names) for the given index in string format seperated by commas. */ Returns Varchar(8000) As BEGIN Declare @SQL varchar(8000) Set @SQL ='' Select @SQL= @SQL +', '+ INDEX_Col(User_name(ObjectProperty(@TableID, 'Ownerid'))+'.'+Object_name(@TableID), @indid, keyno)+ Case indexkey_property(id, indid, keyno, 'isdescending') When 1 Then '(Desc)' Else '' end from sysindexkeys Where id =@Tableid and indid=@Indid Order by id, indid, Keyno IF LEN(@SQL)>2 Select @SQL = SUbString(@SQL, 3, LEN(@SQL)-2) Return @SQL END GO /* @TempTable is used to store the keys in long string format */ Declare @TempTable Table ( ID int , Indid int, ColID Varchar(200), Status int ) Declare @Duplicates Table ( LineID int Identity(1,1), ID int , hasClustered char(3) not null default('NO'), Indid1 int, ColID1 Varchar(200), Status1 int, Desc1 varchar(200), IndID2 int, ColID2 Varchar(200), Status2 int, Desc2 varchar(100) ) Insert into @TempTable Select Id, indid, dbo.GetColid(id, indid), status from Sysindexes where (status & 64)=0 order by id Delete @TempTable Where ColID='' Insert into @Duplicates (ID, IndID1, ColID1, Desc1, Status1, IndID2, ColID2, desc2, status2 ) Select A.ID, A.IndID, A.ColID, '', A.status, B.IndID, B.ColID, '', B.status from @Temptable A, @TempTable B Where A.id = b.id and a.indid<>b.indid and a.colid like b.colid +'%' --This part removes the duplicate entries. Delete @Duplicates Where LineID In ( Select A.LineID from @Duplicates A, @Duplicates B Where A.ID = B.ID and A.IndID1= B.IndID2 and A.IndID2= B.IndID1 and A.LineID>B.LineID) Delete @Duplicates Where LineID In ( Select A.LineID from @Duplicates A, @Duplicates B Where A.ID = B.ID and A.IndID1 = B.IndID2 ) -- Identify the index properties Update @Duplicates Set Desc1 =CASE status1 & 16 WHEN 0 THEN 'Nonclustered' ELSE 'Clustered' END Update @Duplicates Set Desc2 =CASE status2 & 16 WHEN 0 THEN 'Nonclustered' ELSE 'Clustered' END Declare @Desc varchar(20), @Number int Declare spt_Vals Cursor FOR Select name, number from master.dbo.spt_Values Where type ='I' and number in (1,2, 4, 32, 2048, 4096) Order by number Open spt_vals FETCH Next from spt_vals into @Desc, @Number WHILE @@FETCH_STATUS=0 BEGIN Update @Duplicates Set Desc1 = Desc1 + ', '+ @Desc where status1 & @number <>0 Update @Duplicates Set Desc2 = Desc2 + ', '+ @Desc where status2 & @number <>0 FETCH Next from spt_vals into @Desc, @Number END CLOSE spt_Vals DEALLOCATE spt_vals Update @Duplicates Set Desc1 = replace(Desc1, 'unique, primary key', 'primary key'), Desc2 = replace(Desc2, 'unique, primary key', 'primary key') Update @Duplicates Set Desc1 = replace(Desc1, 'unique, unique key', 'unique key'), Desc2 = replace(Desc2, 'unique, unique key', 'unique key') -- Identify whether table has clustered index Update @Duplicates Set HasClustered = 'YES' Where id in ( Select id From sysIndexes Where IndId=1) --Update @Duplicates Set HasClustered = 'NO' Where id in ( --Select id From sysIndexes Where IndId=0) Select User_name(ObjectProperty(A.ID, 'Ownerid'))+'.'+Object_name(a.id) 'Table Name', HasClustered, IA.Name 'Index 1', dbo.GetColList(A.id, A.indid1) 'Keys of Index 1', A.Desc1 'Desc 1', IB.Name 'Index 2', dbo.GetColList(A.id, A.indid2) 'Columns of Index 2', A.Desc2 'Desc 2' from @Duplicates A, SysIndexes IA, Sysindexes IB Where IA.id =A.id and IA.indId = A.IndID1 and IB.ID = A.ID and IB.indId=A.IndID2 order by User_name(ObjectProperty(A.ID, 'Ownerid'))+'.'+Object_name(a.id) /* GO DROP FUNCTION dbo.getColList GO DROP FUNCTION dbo.getColID GO */
'T-SQL' 카테고리의 다른 글
SQLCLR Disk 사이즈 확인 (0) | 2011.08.14 |
---|---|
T-SQL:: TCP 포트 정보 (0) | 2011.08.13 |
DBCC ShrinkFile (0) | 2010.09.06 |
[T-SQL] JOb 수행 시간 완료 계산 (0) | 2010.07.19 |
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 |
You may experience a decrease in query performance after you perform certain database maintenance operations or regular transaction operations in SQL Server 2005
( http://support.microsoft.com/kb/917828 )
2006-10-15 06:03:29.330 spid59 SQL Server has encountered 4 occurrence(s) of cachestore flush for the 'Object Plans' cachestore (part of plan cache) due to some database maintenance or reconfigure operations.
2006-10-15 06:03:29.420 spid59 SQL Server has encountered 4 occurrence(s) of cachestore flush for the 'SQL Plans' cachestore (part of plan cache) due to some database maintenance or reconfigure operations.
2006-10-15 06:03:29.420 spid59 SQL Server has encountered 4 occurrence(s) of cachestore flush for the 'Bound Trees' cachestore (part of plan cache) due to some database maintenance or reconfigure operations.
The whole procedure cache is cleared when certain database level operations are performed in the following scenarios:
· A database has the AUTO_CLOSE database option set to ON. When no user connection references or uses the database, the background task tries to close and shut down the database automatically.
· You run several queries against a database that has default options. Then, the database is dropped.
· A database snapshot for a source database is dropped.
Note Database snapshots are only available in Microsoft SQL Server 2005 Enterprise Edition.
· You change the database state to OFFLINE or ONLINE.
· You successfully rebuild the transaction log for a database.
· You restore a database backup.
· You run the DBCC CHECKDB statement.
Note This is true only in versions of SQL Server 2005 that are earlier than SQL Server 2005 SP2. After you install SQL Server 2005 SP2 or later versions, the whole procedure cache is not flushed when you run the DBCC CHECKDB statement.
· You detach a database.
· You specify one of the following options when you run the ALTER DATABASE statement:
o OFFLINE
o ONLINE
o MODIFY FILEGROUP DEFAULT
o MODIFY_NAME
o MODIFY FILEGROUP READ_WRITE
o COLLATE
o MODIFY FILEGROUP READ_ONLY
o READ_ONLY
o READ_WRITE
· The whole procedure cache is cleared if one of the following server options is changed by the RECONFIGURE statement:
o cross db ownership chaining
o index create memory (KB)
o remote query timeout (s)
o user options
o max text repl size (B)
o cost threshold for parallelism
o max degree of parallelism
o min memory per query (KB)
o query wait (s)
o min server memory (MB)
o max server memory (MB)
o query governor cost limit
Note Procedure cache will not be cleared if the actual value does not change or if the new value for the max server memory server option is set to 0.
'Common Admin' 카테고리의 다른 글
Admin::2000용 TEST DB 생성. (0) | 2011.10.05 |
---|---|
Admin:: SQL Server 에러로 다른 서버에서 Rebuilding 처리 (0) | 2011.08.14 |
Admin::Configuring Windows 2003 ( x64 ) for SQL Server (0) | 2010.12.28 |
Admin:: LOG Rebuild (0) | 2010.11.23 |