반응형
반응형

코드는 계속 수정 될 수 있어야 하기에 어쩔 수 없이 링크로 제공 됩니다.
죄송합니다.

 

http://sqlsql.tistory.com/59

http://sqlsql.tistory.com/170

아래는 추숙님이 작성한 도움되는 자료 입니다.

http://cafe.naver.com/sqlmvp/2611


반응형
반응형

코드는 계속 수정 될 수 있어야 하기에 어쩔 수 없이 링크로 제공 됩니다.
죄송합니다.

 

waitstat 조사용 프로시저 입니다.

 

http://sqlsql.tistory.com/21


반응형
반응형

코드는 계속 수정 될 수 있어야 하기에 어쩔 수 없이 링크로 제공 됩니다.
죄송합니다.

내용으로 백업 할 경우 암호가 걸려 있으니 적절히 수정해서 사용하세요!

http://sqlsql.tistory.com/43

 


반응형
반응형


데이터전송최적화_script.sql


반응형
반응형


병렬처리_실전_쿼리_튜닝_2012_04_23.sql


반응형
반응형

[스크립트 13-4]

DECLARE @LS_BackupJobId       AS uniqueidentifier

DECLARE @LS_PrimaryId  AS uniqueidentifier

DECLARE @SP_Add_RetCode       As int

 

 

EXEC @SP_Add_RetCode = master.dbo.sp_add_log_shipping_primary_database

               @database = N'LogTest'

               ,@backup_directory = N'c:\LogShipping'

               ,@backup_share = N'\\Log1\LogShipping'

               ,@backup_job_name = N'LSBackup_LogTest'

               ,@backup_retention_period = 4320

               ,@backup_compression = 1

               ,@monitor_server = N'Log3'

               ,@monitor_server_security_mode = 1

               ,@backup_threshold = 60

               ,@threshold_alert_enabled = 1

               ,@history_retention_period = 5760

               ,@backup_job_id = @LS_BackupJobId OUTPUT

               ,@primary_id = @LS_PrimaryId OUTPUT

               ,@overwrite = 1

 

 

IF (@@ERROR = 0 AND @SP_Add_RetCode = 0)

BEGIN

 

DECLARE @LS_BackUpScheduleUID As uniqueidentifier

DECLARE @LS_BackUpScheduleID  AS int

 

 

EXEC msdb.dbo.sp_add_schedule

               @schedule_name =N'LSBackupSchedule_LOG11'

               ,@enabled = 1

               ,@freq_type = 4

               ,@freq_interval = 1

               ,@freq_subday_type = 4

               ,@freq_subday_interval = 1

               ,@freq_recurrence_factor = 0

               ,@active_start_date = 20111016

               ,@active_end_date = 99991231

               ,@active_start_time = 0

               ,@active_end_time = 235900

               ,@schedule_uid = @LS_BackUpScheduleUID OUTPUT

               ,@schedule_id = @LS_BackUpScheduleID OUTPUT

 

EXEC msdb.dbo.sp_attach_schedule

               @job_id = @LS_BackupJobId

               ,@schedule_id = @LS_BackUpScheduleID 

 

EXEC msdb.dbo.sp_update_job

               @job_id = @LS_BackupJobId

               ,@enabled = 1

 

 

END

 

 

EXEC master.dbo.sp_add_log_shipping_primary_secondary

               @primary_database = N'LogTest'

               ,@secondary_server = N'Log2'

               ,@secondary_database = N'LogTest'

               ,@overwrite = 1

 

[스크립트 13-5]

DECLARE @LS_Secondary__CopyJobId      AS uniqueidentifier

DECLARE @LS_Secondary__RestoreJobId   AS uniqueidentifier

DECLARE @LS_Secondary__SecondaryId    AS uniqueidentifier

DECLARE @LS_Add_RetCode       As int

 

 

EXEC @LS_Add_RetCode = master.dbo.sp_add_log_shipping_secondary_primary

               @primary_server = N'LOG1'

               ,@primary_database = N'LogTest'

               ,@backup_source_directory = N'\\Log1\LogShipping'

               ,@backup_destination_directory = N'c:\LogShipping'

               ,@copy_job_name = N'LSCopy_LOG1_LogTest'

               ,@restore_job_name = N'LSRestore_LOG1_LogTest'

               ,@file_retention_period = 4320

               ,@monitor_server = N'Log3'

               ,@monitor_server_security_mode = 1

               ,@overwrite = 1

               ,@copy_job_id = @LS_Secondary__CopyJobId OUTPUT

               ,@restore_job_id = @LS_Secondary__RestoreJobId OUTPUT

               ,@secondary_id = @LS_Secondary__SecondaryId OUTPUT

 

IF (@@ERROR = 0 AND @LS_Add_RetCode = 0)

BEGIN

 

DECLARE @LS_SecondaryCopyJobScheduleUID      As uniqueidentifier

DECLARE @LS_SecondaryCopyJobScheduleID       AS int

 

 

EXEC msdb.dbo.sp_add_schedule

               @schedule_name =N'DefaultCopyJobSchedule'

               ,@enabled = 1

               ,@freq_type = 4

               ,@freq_interval = 1

               ,@freq_subday_type = 4

               ,@freq_subday_interval = 1

               ,@freq_recurrence_factor = 0

               ,@active_start_date = 20111016

               ,@active_end_date = 99991231

               ,@active_start_time = 0

               ,@active_end_time = 235900

               ,@schedule_uid = @LS_SecondaryCopyJobScheduleUID OUTPUT

               ,@schedule_id = @LS_SecondaryCopyJobScheduleID OUTPUT

 

EXEC msdb.dbo.sp_attach_schedule

               @job_id = @LS_Secondary__CopyJobId

               ,@schedule_id = @LS_SecondaryCopyJobScheduleID 

 

DECLARE @LS_SecondaryRestoreJobScheduleUID   As uniqueidentifier

DECLARE @LS_SecondaryRestoreJobScheduleID    AS int

 

 

EXEC msdb.dbo.sp_add_schedule

               @schedule_name =N'DefaultRestoreJobSchedule'

               ,@enabled = 1

               ,@freq_type = 4

               ,@freq_interval = 1

               ,@freq_subday_type = 4

               ,@freq_subday_interval = 15

               ,@freq_recurrence_factor = 0

               ,@active_start_date = 20111016

               ,@active_end_date = 99991231

               ,@active_start_time = 0

               ,@active_end_time = 235900

               ,@schedule_uid = @LS_SecondaryRestoreJobScheduleUID OUTPUT

               ,@schedule_id = @LS_SecondaryRestoreJobScheduleID OUTPUT

 

EXEC msdb.dbo.sp_attach_schedule

               @job_id = @LS_Secondary__RestoreJobId

               ,@schedule_id = @LS_SecondaryRestoreJobScheduleID 

 

 

END

 

 

DECLARE @LS_Add_RetCode2      As int

 

 

IF (@@ERROR = 0 AND @LS_Add_RetCode = 0)

BEGIN

 

EXEC @LS_Add_RetCode2 = master.dbo.sp_add_log_shipping_secondary_database

               @secondary_database = N'LogTest'

               ,@primary_server = N'LOG1'

               ,@primary_database = N'LogTest'

               ,@restore_delay = 0

               ,@restore_mode = 0

               ,@disconnect_users     = 0

               ,@restore_threshold = 45  

               ,@threshold_alert_enabled = 1

               ,@history_retention_period    = 5760

               ,@overwrite = 1

               ,@ignoreremotemonitor = 1

 

 

END

 

 

IF (@@error = 0 AND @LS_Add_RetCode = 0)

BEGIN

 

EXEC msdb.dbo.sp_update_job

               @job_id = @LS_Secondary__CopyJobId

               ,@enabled = 1

 

EXEC msdb.dbo.sp_update_job

               @job_id = @LS_Secondary__RestoreJobId

               ,@enabled = 1

 

END

 

[스크립트 13-6

EXEC msdb.dbo.sp_processlogshippingmonitorsecondary

               @mode = 1

               ,@secondary_server = N'Log2'

               ,@secondary_database = N'LogTest'

               ,@secondary_id = N''

               ,@primary_server = N'LOG1'

               ,@primary_database = N'LogTest'

               ,@restore_threshold = 45  

               ,@threshold_alert = 14420

               ,@threshold_alert_enabled = 1

               ,@history_retention_period    = 5760

               ,@monitor_server = N'Log3'

               ,@monitor_server_security_mode = 1

 

반응형
반응형

[스크립트 11-10]

--인증키생성

create master key encryption by password = 'www.SQLTAG.org';

GO

 

--인증키 추가( 서버(A), 미러 서버(B), 모니터 서버(C) 구분하자)

create certificate SQLTAG_A_Cert with subject = 'SQLTAG_A certificate', start_date = '2011-01-01', expiry_date = '2020-01-01';

GO

 

[스크립트 11-11]

--인증키백업

Backup certificate SQLTAG_Cert to file = 'C:\SQLTAG_A_Cert.cer';

 

[스크립트 11-12]

--ENDPOINT 생성

Create endpoint Mirroring state = started

as tcp(listener_port = 5022, listener_ip = all)

for data_mirroring (authentication = certificate SQLTAG_A_Cert, encryption = required, role = partner);

GO

 

[스크립트 11-13]

--미러 서버가 사용 계정 생성.

create login SQLTAG_B_Login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_B_User from login SQLTAG_B_Login;

GO

 

--미러 서버 인증서 등록.

Create certificate SQLTAG_B_cert Authorization SQLTAG_B_user From file = 'c:\SQLTAG_B_cert.cer';

GO

 

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_B_Login];

GO

 

[스크립트 11-14]

-- 모니터링 서버가 사용 계정 생성.

create login SQLTAG_C_Login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_C_User from login SQLTAG_C_Login;

GO

 

-- 모니터링 서버 인증서 등록.

Create certificate SQLTAG_C_cert Authorization SQLTAG_C_User From file = 'C:\SQLTAG_C_cert.cer';

GO

 

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_C_Login];

GO

 

[스크립트 11-15]

-- 미러 서버 파트너 설정

alter database MirrorTest set partner ='TCP://SECOND2008R2.localdomain:5022';

GO

 

-- 모니터링 서버 파트너 설정

alter database MirrorTest set witness = 'TCP://THIRD2008R2.localdomain:5022';

GO

 

[스크립트 11-16]

-- 서버가 사용할 계정 생성.

create login SQLTAG_A_login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_A_User from login SQLTAG_A_login;

GO

 

-- 서버의 인증서 등록

Create certificate SQLTAG_A_cert Authorization SQLTAG_A_user From file = 'C:\SQLTAG_A_cert.cer';

GO

 

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_A_login];

GO

 

[스크립트 11-17]

--모니터링 서버가 사용할 계정 생성

create login SQLTAG_C_login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_C_user from login SQLTAG_C_login;

GO

 

--모니터링 서버의 인증서 등록

Create certificate SQLTAG_C_cert Authorization SQLTAG_C_user From file = 'C:\SQLTAG_C_cert.cer';

GO

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_C_login];

GO

 

[스크립트 11-18]

-- 파트너 설정

alter database Mu_Log set partner = 'TCP://first2008r2:5022';

 

[스크립트 11-19]

-- 서버 사용할 계정 생성

create login SQLTAG_A_login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_A_user from login SQLTAG_A_login;

GO

 

-- 서버 인증키 등록

Create certificate SQLTAG_A_cert Authorization SQLTAG_A_user From file = 'c:\SQLTAG_A_cert.cer';

GO

 

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_A_login];

GO

 

[스크립트 11-20]

--미러 서버 사용할 계정 생성

create login SQLTAG_B_login with PASSWORD = 'www.SQLTAG.org';

GO

 

create user SQLTAG_B_user from login SQLTAG_B_login;

GO

 

--미러 서버 사용할 인증키 등록

Create certificate SQLTAG_B_cert Authorization SQLTAG_B_user From file = 'c:\SQLTAG_B_cert.cer';

GO

 

Grant CONNECT ON Endpoint::Mirroring to [SQLTAG_B_login];

GO

 

[스크립트 11-27]

--스크립트 제공(한국마이크로소프트 송혁)

USE MSDB

GO

 

ALTER DATABASE [msdb] SET ENABLE_BROKER

GO

 

CREATE TABLE tbl_SQLTAG

(

        MirrorStateChange int,

    DBName varchar(100),

    ServerName varchar(100),

    PostTime datetime,

    SPID int,

    TextData nvarchar(500),

    DatabaseID int,

    TransactionsID int,

    StartTime datetime

 )

GO

 

CREATE proc Failover_SQLTAG

as

DECLARE @SQL VARCHAR(8000);

Declare @Message XML

 

WHILE 1=1

BEGIN

WAITFOR(

RECEIVE TOP (1) @Message = Cast(message_body as XML) from DBMirrorQueue

), TIMEOUT 100;

 

IF (@@ROWCOUNT <> 0)

BEGIN

               insert into Failover_SQLTAG values(

               @Message.value('(/EVENT_INSTANCE/State)[1]', 'int')

               ,@Message.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'sysname')

               ,@Message.value('(/EVENT_INSTANCE/ServerName)[1]', 'sysname')

               ,@Message.value('(/EVENT_INSTANCE/PostTime)[1]', 'datetime')

               ,@Message.value('(/EVENT_INSTANCE/SPID)[1]', 'int')

               ,@Message.value('(/EVENT_INSTANCE/TextData)[1]', 'nvarchar(500)')

               ,@Message.value('(/EVENTr_INSTANCE/DatabaseID)[1]', 'int')

               ,@Message.value('(/EVENT_INSTANCE/TransactionsID)[1]', 'int')

               ,@Message.value('(/EVENT_INSTANCE/StartTime)[1]', 'datetime')

               ) 

 

               IF @Message.value('(/EVENT_INSTANCE/State)[1]', 'int')  IN (7,8)

               BEGIN

               SET @SQL = 'USE MASTER  '

               SELECT @SQL = @SQL + 'ALTER DATABASE '+db_name(database_id)

               +' SET PARTNER FAILOVER; '

               FROM sys.database_mirroring WHERE mirroring_state=4 and mirroring_role = 1

                       --SELECT @SQL

                       exec (@sql)

               END

              

               IF @Message.value('(/EVENT_INSTANCE/State)[1]', 'int')  IN (11) -- agent disable

               BEGIN

                      

               SET @SQL = 'USE MSDB '

               SELECT @SQL = @SQL + 'exec sp_update_job @job_id = '''+cast(job_id as varchar(100))+''', @enabled = 0;' 

               FROM msdb.dbo.sysjobs

               where name like '[[mirroring%' ESCAPE '['

               --SELECT @SQL

               exec (@sql)

               END

              

               IF @Message.value('(/EVENT_INSTANCE/State)[1]', 'int')  IN (13) -- agent enable

               BEGIN

                       --DECLARE @SQL VARCHAR(1000)

               SET @SQL = 'USE MSDB '

               SELECT @SQL = @SQL + 'exec sp_update_job @job_id = '''+cast(job_id as varchar(100))+''', @enabled = 1;' 

               FROM msdb.dbo.sysjobs

               where name like '[[mirroring%' ESCAPE '['

                                                            

               --SELECT @SQL

               exec (@sql)

        END

END

END

GO

GO

 

/* Create Queue */

    ALTER Queue DBMirrorQueue

        With Status = On,

        Retention = Off,

        Activation (

        Procedure_Name = dbo.Failover_SQLTAG,

            Max_Queue_Readers = 1,

            Execute As Self)

GO

/* Create Service */

    Create Service DBMirrorService

        On Queue DBMirrorQueue ([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification]);

GO

/* Create Route*/

    Create Route DBMirrorRoute

        With Service_Name = 'DBMirrorService',

        Address = 'Local';

GO

/* Create Event */

    Create Event Notification DBMirrorStateChange

        On Server

        For DATABASE_MIRRORING_STATE_CHANGE

        To Service 'DBMirrorService', 'current database';

 

[예제실습 소스 코드]

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

using System.Data.SqlClient;

 

namespace MirrorTest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        SqlConnection myConn;

        SqlCommand myCmd;

        SqlDataReader myReader;

 

        private string conn = "Server=First2008r2; Failover Partner=Second2008r2; Database=MirrorTest; user=sa; password=패스워드";

        private string StrMsg = "";

       

       

        private void btn_Start_Click(object sender, EventArgs e)

        {

            this.myConn = new SqlConnection();

            this.myConn.ConnectionString = conn;

           

            this.myCmd = new SqlCommand();

            this.myCmd.CommandType = System.Data.CommandType.Text;

            this.myCmd.Connection = myConn;

 

            myConn.Open();

            myCmd.CommandText = this.txt_Query.Text;

            myCmd.ExecuteNonQuery();

 

            this.myReader = myCmd.ExecuteReader();

 

            this.myReader.Read();

 

            this.txt_Result.Text = myReader.GetSqlString(0).ToString(); ;

         

 

 

           

 

        }

 

        private void btn_Stop_Click(object sender, EventArgs e)

        {

            myConn.Close();

 

        }

    }

}

 

반응형
반응형

블럭관련 정보 출력


-- @@ 바뀐 내용
- 어뷰징 확인을 위해 동일한 리소스를 얼마나 많은 사람들이 대기하고 있는지 보여줌
- set rowcount로 페이지를 자르던 부분을 top 구문으로 변경
- 락인포 5000건 -> 200건

use master

go


if object_id('sp_lock2') is not null
drop proc sp_lock2
go

 

 

create proc sp_lock2
as

set nocount on
set transaction isolation level read uncommitted

-- CTRL - T 모드로 변경 하세요
-- 도구 > 옵션 > 결과 텍스트 > 글꼴 > 굴림체
-- 마스터 에서 돌리세요
-- 최초 김민석
-- SQL Server MVP 2006~2009
-- by minsouk@hotmail.com
-- 수정 하만철
-- 20100624 세션정보 추가 김민석

-- 20110825 세션정보 버전정보 연산자 수정


/**** object view 생성을 위로 올렸습니다~!! ****/
declare @viewheader varchar(8000), @viewbody varchar(8000)
select @viewheader ='' , @viewbody =''
if object_id('v_objlist') is not null
drop view v_objlist
set @viewheader = 'create view dbo.v_objlist as '
select
@viewbody = @viewbody + 'union all select db_id('''+quotename(name)+''') dbid
 , name collate database_default name
, id
 from '+quotename(name)+'.dbo.sysobjects '+char(13)+char(10)
from master.dbo.sysdatabases
where dbid > 4
select @viewbody = stuff(@viewbody, 1,10, '')
exec (@viewheader + @viewbody)

 

print N'######################################################################'
print N'세션정보'
print N'######################################################################'

DECLARE @VERSION INT
SELECT @VERSION = SUBSTRING(CAST(SERVERPROPERTY('PRODUCTVERSION') AS VARCHAR(100))
 , 1, CHARINDEX('.',CAST(SERVERPROPERTY('PRODUCTVERSION') AS VARCHAR(100)))-1)

 

IF @VERSION >= 9 BEGIN
SELECT SESSION_ID
 , CASE TRANSACTION_ISOLATION_LEVEL
WHEN 0 THEN '지정되지 않음'
WHEN 1 THEN '커밋되지 않은 읽기'
WHEN 2 THEN '커밋된 읽기'
WHEN 3 THEN '##반복 읽기##'
WHEN 4 THEN '@@직렬화 가능@@'
WHEN 5 THEN 'XX스냅숏XX' ELSE '?' END
, *
FROM SYS.DM_EXEC_SESSIONS
 WHERE SESSION_ID > 50
END


print N'######################################################################'
print N'락인포 어뷰징 확인 200개 ver 0.1'
print N'######################################################################'

select top 200
 rsc_text
 , count(*) cnt
 , case req_status
when 1 then N'허가됨'
when 2 then N'변환중'
when 3 then N'대기중'
 end req_status
 , max(left(db_name(rsc_dbid),30)+case when len(c.name) > 30 then '...' else '' end) dbname
, max(left(c.name,30)+case when len(c.name) > 30 then '...' else '' end) objname
, max(rsc_indid) IndId
 , max(case rsc_type
when 1 then null
 when 2 then 'DB'
 when 3 then 'File'
 when 4 then 'Index'
 when 5 then 'Table'
 when 6 then 'Page'
 when 7 then 'Key'
 when 8 then 'Extent'
 when 9 then 'RID'
 when 10 then 'App'
 end) Type
 , max(case req_mode --(0,3,6,7,8,9)
 when 0 then null
 when 1 then N'Sch-S:스키마 안전성'
when 2 then N'Sch-M:스키마 수정'
when 3 then N'S:공유'
when 4 then N'U:업데이트'
when 5 then N'X:단독'
when 6 then N'IS:내재 공유'
when 7 then N'IU:내재 업데이트'
when 8 then N'IX:내재 단독'
when 9 then N'SIU:공유 내재 업데이트'
when 10 then N'SIX:공유 내재 단독'
when 11 then N'UIX:업데이트 내재 단독'
when 12 then N'BU:대량 작업'
when 13 then N'RangeS_S:공유 키 범위 및 공유 리소스'
when 14 then N'RangeS_U:공유 키 범위 및 업데이트 리소스'
when 15 then N'RangeI_N:삽입 키 범위 및 Null 리소스'
when 16 then N'RangeI_S:RangeI_N 및 S 잠금의 겹침으로 만들어진 키 범위 변환'
when 17 then N'RangeI_U:RangeI_N 및 U 잠금의 겹침으로 만들어진 키 범위 변환'
when 18 then N'RangeI_X:RangeI_N 및 X 잠금의 겹침으로 만들어진 키 범위 변환'
when 19 then N'RangeX_S:RangeI_N 및 RangeS_S. 잠금의 겹침으로 만들어진 키 범위 변환'
when 20 then N'RangeX_U:RangeI_N 및 RangeS_U 잠금의 겹침으로 만들어진 키 범위 변환'
when 21 then N'RangeX_X:단독 키 범위 및 단독 리소스'
 end) Mode
 , max(case req_ownertype
when 1 then N'트랜잭션'
when 2 then N'커서'
when 3 then N'세션'
when 4 then N'ExSession'
 end) req_ownertype
from
master.dbo.syslockinfo a with (nolock)
 left join master.dbo.v_objlist c with (nolock)
 on c.dbid = a.rsc_dbid
 and c.id = a.rsc_objid
where
req_spid <> @@spid
-- and req_status = 1
 and rsc_type <> 2
group by req_status, rsc_text
order by req_status, count(*) desc


/**** N' 추가했습니다~!! ****/
print N'######################################################################'
print N'헤드블럭만 보기 by minsouk@hotmail.com ver 0.1'
print N'######################################################################'

select *
from master.dbo.sysprocesses
where blocked = 0
and spid in (select blocked from master.dbo.sysprocesses where blocked <> 0)

print N'######################################################################'
print N'헤드블럭 쿼리보기 by minsouk@hotmail.com ver 0.1'
print N'######################################################################'

 

/**** adhoc 경우 dbid, objectid 가 null 이라 dbname 보여주기위해 dbid 추가 했습니다!! ****/
declare cur_headblock cursor fast_forward
for
select spid, sql_handle, dbid
 from master.dbo.sysprocesses
where blocked = 0
and spid in (select blocked from master.dbo.sysprocesses where blocked <> 0)
declare @spid varchar(6)
declare @dbid int
declare @handle varbinary(64);
open cur_headblock
fetch next from cur_headblock into @spid, @handle, @dbid
while (@@fetch_status != -1)
begin
 print '#########################'
 print 'dbcc inputbuffer for spid ' + @spid
print '#########################'

 /***** adhoc, proc 구분하고 objname 보게 바꿔봤습니다~!! ****/
 select case when fn.dbid is null then 'AdHoc' else 'Proc' end as qry_type, db_name(@dbid)
dbname, vo.name as objname, [text]
from ::fn_get_sql(@handle) fn
 left outer join v_objlist vo on fn.dbid = vo.dbid and fn.objectid = vo.id
 exec ('dbcc inputbuffer (' + @spid + ')')
 fetch next from cur_headblock into @spid, @handle, @dbid
end
deallocate cur_headblock

print N'######################################################################'
print N'락트리 보기 by minsouk@hotmail.com ver 0.2'
print N'######################################################################'

if object_id ('tempdb..#tbl_sysprocesses') is not null
 drop table #tbl_sysprocesses

create table #tbl_sysprocesses
(
depth int
 , tree varchar(7000)
 , spid int
 , blocked int
 --, sql_handle varbinary(64)
)

insert into #tbl_sysprocesses (depth, tree, spid, blocked)
select 0, cast(spid as varchar(100)) spid , spid, blocked
from master.dbo.sysprocesses
where blocked = 0
and spid in (select blocked from master.dbo.sysprocesses where blocked <> 0)

declare @max_depth int
set @max_depth = 5

while (1=1)
begin
insert into #tbl_sysprocesses (depth, tree, spid, blocked)
select a.depth + 1 depth , a.tree + ' > ' +cast(b.spid as varchar(8000)) tree , b.spid, b.blocked
 from #tbl_sysprocesses a
 inner join master.dbo.sysprocesses b
 on a.spid = b.blocked
 where depth in (select max(depth) from #tbl_sysprocesses)
 and b.spid <> b.blocked
 if @@rowcount = 0 break
 set @max_depth = @max_depth - 1
 if @max_depth <= 1 break
end

declare @cnt varchar(10)
select @cnt = cast(cnt as varchar(10)) from ( select count(*) cnt from sysprocesses where blocked <> 0 ) a

print N'######################################################################'
print N'블럭카운트 : '+@cnt
print N'######################################################################'

select convert(char(10), cast((b.waittime / 1000) * 1.1574074074074073E-5 as datetime) , 108) as[hh:mm:ss]
 , left(a.tree, 40)+case when len(a.tree) > 40 then '...' else '' end locktree, b.*
from #tbl_sysprocesses a
 inner join master.dbo.sysprocesses b
 on a.spid = b.spid
order by tree


print N'######################################################################'
print N'######################################################################'
print N'######################################################################'
print N'락인포 보기 by minsouk@hotmail.com ver 0.5'
print N'######################################################################'
print N'######################################################################'
print N'######################################################################'
print N''

/*
if object_id ('dbo.usp_create_v_objlist') is not null
drop proc dbo.usp_create_v_objlist
*/

--exec dbo.usp_create_v_objlist

--set rowcount 200

print N'######################################################################'
print N'락인포 허가 200개 exclude rsc_type db by minsouk@hotmail.com ver 0.6'
print N'######################################################################'

select top 200
 req_spid spid
 , left(db_name(rsc_dbid),30)+case when len(c.name) > 30 then '...' else '' end dbname
, left(c.name,30)+case when len(c.name) > 30 then '...' else '' end objname
, rsc_indid IndId
 , case rsc_type
when 1 then null
 when 2 then 'DB'
 when 3 then 'File'
 when 4 then 'Index'
 when 5 then 'Table'
 when 6 then 'Page'
 when 7 then 'Key'
 when 8 then 'Extent'
 when 9 then 'RID'
 when 10 then 'App'
 end Type
 , rsc_type
 , rsc_text
 , case req_mode --(0,3,6,7,8,9)
 when 0 then null
 when 1 then N'Sch-S:스키마 안전성'
when 2 then N'Sch-M:스키마 수정'
when 3 then N'S:공유'
when 4 then N'U:업데이트'
when 5 then N'X:단독'
when 6 then N'IS:내재 공유'
when 7 then N'IU:내재 업데이트'
when 8 then N'IX:내재 단독'
when 9 then N'SIU:공유 내재 업데이트'
when 10 then N'SIX:공유 내재 단독'
when 11 then N'UIX:업데이트 내재 단독'
when 12 then N'BU:대량 작업'
when 13 then N'RangeS_S:공유 키 범위 및 공유 리소스'
when 14 then N'RangeS_U:공유 키 범위 및 업데이트 리소스'
when 15 then N'RangeI_N:삽입 키 범위 및 Null 리소스'
when 16 then N'RangeI_S:RangeI_N 및 S 잠금의 겹침으로 만들어진 키 범위 변환'
when 17 then N'RangeI_U:RangeI_N 및 U 잠금의 겹침으로 만들어진 키 범위 변환'
when 18 then N'RangeI_X:RangeI_N 및 X 잠금의 겹침으로 만들어진 키 범위 변환'
when 19 then N'RangeX_S:RangeI_N 및 RangeS_S. 잠금의 겹침으로 만들어진 키 범위 변환'
when 20 then N'RangeX_U:RangeI_N 및 RangeS_U 잠금의 겹침으로 만들어진 키 범위 변환'
when 21 then N'RangeX_X:단독 키 범위 및 단독 리소스'
 end Mode
 , req_mode
 , case req_status
when 1 then N'허가됨'
when 2 then N'변환중'
when 3 then N'대기중'
 end req_status
 , req_refcnt
, req_lifetime
, req_ecid [req_ecid (isParallel)]
 , case req_ownertype
when 1 then N'트랜잭션'
when 2 then N'커서'
when 3 then N'세션'
when 4 then N'ExSession'
 end req_ownertype
 , req_transactionID
 , req_transactionUOW [req_transactionUOW (isDTC)]
from
master.dbo.syslockinfo a with (nolock)
 left join master.dbo.v_objlist c with (nolock)
 on c.dbid = a.rsc_dbid
 and c.id = a.rsc_objid
where
req_spid <> @@spid
 and req_status = 1
 and rsc_type <> 2
order by
spid -- 정렬

print N'######################################################################'
print N'락인포 변환 200개 by minsouk@hotmail.com ver 0.5'
print N'######################################################################'

select top 200
 req_spid spid
 , left(db_name(rsc_dbid),30)+case when len(c.name) > 30 then '...' else '' end dbname
, left(c.name,30)+case when len(c.name) > 30 then '...' else '' end objname
, rsc_indid IndId
 , case rsc_type
when 1 then null
 when 2 then 'DB'
 when 3 then 'File'
 when 4 then 'Index'
 when 5 then 'Table'
 when 6 then 'Page'
 when 7 then 'Key'
 when 8 then 'Extent'
 when 9 then 'RID'
 when 10 then 'App'
 end Type
 , rsc_type
 , rsc_text
 , case req_mode --(0,3,6,7,8,9)
 when 0 then null
 when 1 then N'Sch-S:스키마 안전성'
when 2 then N'Sch-M:스키마 수정'
when 3 then N'S:공유'
when 4 then N'U:업데이트'
when 5 then N'X:단독'
when 6 then N'IS:내재 공유'
when 7 then N'IU:내재 업데이트'
when 8 then N'IX:내재 단독'
when 9 then N'SIU:공유 내재 업데이트'
when 10 then N'SIX:공유 내재 단독'
when 11 then N'UIX:업데이트 내재 단독'
when 12 then N'BU:대량 작업'
when 13 then N'RangeS_S:공유 키 범위 및 공유 리소스'
when 14 then N'RangeS_U:공유 키 범위 및 업데이트 리소스'
when 15 then N'RangeI_N:삽입 키 범위 및 Null 리소스'
when 16 then N'RangeI_S:RangeI_N 및 S 잠금의 겹침으로 만들어진 키 범위 변환'
when 17 then N'RangeI_U:RangeI_N 및 U 잠금의 겹침으로 만들어진 키 범위 변환'
when 18 then N'RangeI_X:RangeI_N 및 X 잠금의 겹침으로 만들어진 키 범위 변환'
when 19 then N'RangeX_S:RangeI_N 및 RangeS_S. 잠금의 겹침으로 만들어진 키 범위 변환'
when 20 then N'RangeX_U:RangeI_N 및 RangeS_U 잠금의 겹침으로 만들어진 키 범위 변환'
when 21 then N'RangeX_X:단독 키 범위 및 단독 리소스'
 end Mode
 , req_mode
 , case req_status
when 1 then N'허가됨'
when 2 then N'변환중'
when 3 then N'대기중'
 end req_status
 , req_refcnt
, req_lifetime
, req_ecid [req_ecid (isParallel)]
 , case req_ownertype
when 1 then N'트랜잭션'
when 2 then N'커서'
when 3 then N'세션'
when 4 then N'ExSession'
 end req_ownertype
 , req_transactionID
 , req_transactionUOW [req_transactionUOW (isDTC)]
from
master.dbo.syslockinfo a with (nolock)
 left join master.dbo.v_objlist c with (nolock)
 on c.dbid = a.rsc_dbid
 and c.id = a.rsc_objid
where
req_spid <> @@spid and req_status = 2
order by
spid -- 정렬

print N'######################################################################'
print N'락인포 대기 200개 by minsouk@hotmail.com ver 0.5'
print N'######################################################################'

select top 200
 req_spid spid
 , left(db_name(rsc_dbid),30)+case when len(c.name) > 30 then '...' else '' end dbname
, left(c.name,30)+case when len(c.name) > 30 then '...' else '' end objname
, rsc_indid IndId
 , case rsc_type
when 1 then null
 when 2 then 'DB'
 when 3 then 'File'
 when 4 then 'Index'
 when 5 then 'Table'
 when 6 then 'Page'
 when 7 then 'Key'
 when 8 then 'Extent'
 when 9 then 'RID'
 when 10 then 'App'
 end Type
 , rsc_type
 , rsc_text
 , case req_mode --(0,3,6,7,8,9)
 when 0 then null
 when 1 then N'Sch-S:스키마 안전성'
when 2 then N'Sch-M:스키마 수정'
when 3 then N'S:공유'
when 4 then N'U:업데이트'
when 5 then N'X:단독'
when 6 then N'IS:내재 공유'
when 7 then N'IU:내재 업데이트'
when 8 then N'IX:내재 단독'
when 9 then N'SIU:공유 내재 업데이트'
when 10 then N'SIX:공유 내재 단독'
when 11 then N'UIX:업데이트 내재 단독'
when 12 then N'BU:대량 작업'
when 13 then N'RangeS_S:공유 키 범위 및 공유 리소스'
when 14 then N'RangeS_U:공유 키 범위 및 업데이트 리소스'
when 15 then N'RangeI_N:삽입 키 범위 및 Null 리소스'
when 16 then N'RangeI_S:RangeI_N 및 S 잠금의 겹침으로 만들어진 키 범위 변환'
when 17 then N'RangeI_U:RangeI_N 및 U 잠금의 겹침으로 만들어진 키 범위 변환'
when 18 then N'RangeI_X:RangeI_N 및 X 잠금의 겹침으로 만들어진 키 범위 변환'
when 19 then N'RangeX_S:RangeI_N 및 RangeS_S. 잠금의 겹침으로 만들어진 키 범위 변환'
when 20 then N'RangeX_U:RangeI_N 및 RangeS_U 잠금의 겹침으로 만들어진 키 범위 변환'
when 21 then N'RangeX_X:단독 키 범위 및 단독 리소스'
 end Mode
 , req_mode
 , case req_status
when 1 then N'허가됨'
when 2 then N'변환중'
when 3 then N'대기중'
 end req_status
 , req_refcnt
, req_lifetime
, req_ecid [req_ecid (isParallel)]
 , case req_ownertype
when 1 then N'트랜잭션'
when 2 then N'커서'
when 3 then N'세션'
when 4 then N'ExSession'
 end req_ownertype
 , req_transactionID
 , req_transactionUOW [req_transactionUOW (isDTC)]
from
master.dbo.syslockinfo a with (nolock)
 left join master.dbo.v_objlist c with (nolock)
 on c.dbid = a.rsc_dbid
 and c.id = a.rsc_objid
where
req_spid <> @@spid
 and req_status = 3
order by
spid -- 정렬

set rowcount 0

print N'######################################################################'
print N'블럭되는 쿼리보기 sql_handle 별 50개 by minsouk@hotmail.com ver 0.2'
print N'######################################################################'

declare cur_blocked cursor fast_forward
for
select top 50 max(spid) spid, sql_handle, max(dbid) dbid from sysprocesses where blocked <> 0
group by sql_handle
--declare @spid varchar(6)
--declare @handle varbinary(64)
open cur_blocked
fetch next from cur_blocked into @spid, @handle, @dbid
while (@@fetch_status != -1)
begin
 print '|||||||||||||||||||||||||'
 print 'dbcc inputbuffer for spid ' + @spid
 print '|||||||||||||||||||||||||'
 select case when fn.dbid is null then 'AdHoc' else 'Proc' end as qry_type, db_name(@dbid)
dbname, vo.name as objname, [text]
from ::fn_get_sql(@handle) fn
 left outer join v_objlist vo on fn.dbid = vo.dbid and fn.objectid = vo.id
 exec ('dbcc inputbuffer (' + @spid + ')')
 fetch next from cur_blocked into @spid, @handle, @dbid
end
deallocate cur_blocked

go

 

exec sp_lock2

반응형

+ Recent posts

반응형