30
SQL Server 2000 SQL Server 2000 세세세 세세세 Stored Procedure Stored Procedure 세세 세세 : : 세세세 세세세 http:// http:// mssql.ce.ro mssql.ce.ro

SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Embed Size (px)

DESCRIPTION

저장프로시져 - 무엇 ?  서버에 컴파일 되어 저장된 SQL 문에 이름이 붙은 집합  모든 SQL 문장 사용 가능 cf. VIEW 나 trigger 는 일부 문장 혹은 SELECT 문만 가능 cf. VIEW 나 trigger 는 일부 문장 혹은 SELECT 문만 가능 예 ) 예 ) SELECT pub_id, title_id, price, pubdate FROM titles where price is NOT NULL order by pub_id COMPUTE avg(price) BY pub_id COMPUTE avg(price)

Citation preview

Page 1: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

SQL Server 2000 SQL Server 2000 세미나세미나Stored ProcedureStored Procedure

강사강사 : : 정원혁정원혁http://http://mssql.ce.romssql.ce.ro

Page 2: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

차 례차 례 무엇무엇 ?? 매개 변수 매개 변수 / Return/ Return 일반 일반 SQL SQL 문장과 프로시저의 차이문장과 프로시저의 차이 컴파일이 성능에 미치는 영향컴파일이 성능에 미치는 영향 컴파일 해야만 하는 경우컴파일 해야만 하는 경우 exec/ sp_executesql / exec/ sp_executesql /

sp_prepare / sp_executesp_prepare / sp_execute 시스템 프로시저 내가 만들기시스템 프로시저 내가 만들기 디버깅디버깅

Page 3: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

저장프로시져 저장프로시져 - - 무엇무엇 ?? 서버에 컴파일 되어 저장된 서버에 컴파일 되어 저장된 SQL SQL 문에 이름이 문에 이름이

붙은 집합붙은 집합 모든 모든 SQL SQL 문장 사용 가능문장 사용 가능

cf. VIEW cf. VIEW 나 나 triggertrigger 는 일부 문장 혹은 는 일부 문장 혹은 SELECT SELECT 문만 가능문만 가능

예예 ))SELECT pub_id, title_id, price, pubdateSELECT pub_id, title_id, price, pubdateFROM titlesFROM titleswhere price is NOT NULLwhere price is NOT NULLorder by pub_idorder by pub_idCOMPUTE avg(price) BY pub_idCOMPUTE avg(price) BY pub_idCOMPUTE avg(price)COMPUTE avg(price)

Page 4: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

저장프로시져 저장프로시져 - - 무엇무엇 ??CREATE PROC[EDURE] procedure_name [;number]CREATE PROC[EDURE] procedure_name [;number] [ {@parameter data_type} [VARYING] [ {@parameter data_type} [VARYING] [= default] [OUTPUT] ][= default] [OUTPUT] ] [,...n][,...n][WITH { RECOMPILE [WITH { RECOMPILE | ENCRYPTION | ENCRYPTION | RECOMPILE, ENCRYPTION } ]| RECOMPILE, ENCRYPTION } ][FOR REPLICATION][FOR REPLICATION]ASAS sql_statement [...n]sql_statement [...n]------------------------------------------------------------------------CREATE PROC[EDURE]CREATE PROC[EDURE]DROP PROC[EDURE]DROP PROC[EDURE]

Page 5: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

매개변수매개변수create PROC p1create PROC p1asasset nocount onset nocount onSELECT TOP 1 title_id,price FROM titlesSELECT TOP 1 title_id,price FROM titlesUPDATE titles set price = price *2UPDATE titles set price = price *2SELECT TOP 1 title_id,price FROM titlesSELECT TOP 1 title_id,price FROM titlesset nocount offset nocount offGoGo----------------------------------------------------------------------------------------------------------------------------------

alter PROC p1alter PROC p1@a@a numeric(10, 3)numeric(10, 3)

asasset nocount onset nocount onSELECT TOP 1 title_id,price FROM titlesSELECT TOP 1 title_id,price FROM titlesUPDATE titles set price = price UPDATE titles set price = price *@a*@aSELECT TOP 1 title_id,price FROM titlesSELECT TOP 1 title_id,price FROM titlesset nocount offset nocount offgogo

Page 6: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

매개변수매개변수 22alter PROC p1alter PROC p1

@a @a numeric(10, 5) = 2numeric(10, 5) = 2,, @b@b varchar(2000)varchar(2000)asasSET NOCOUNT ONSET NOCOUNT ONSELECT TOP 5 title_id, type, price FROM titles SELECT TOP 5 title_id, type, price FROM titles where where

type like @btype like @bUPDATE titles set price = price * @aUPDATE titles set price = price * @a where where

type like @btype like @bSELECT TOP 5 title_id, type, price FROM titles SELECT TOP 5 title_id, type, price FROM titles where where

type like @btype like @bGoGo----------------------------------------------------------------------------------------------------------------------------------

Exec p1 Exec p1 .5, .5, '%cook''%cook'

Page 7: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

매개변수매개변수 33alter PROC p1alter PROC p1

@a @a numeric(10, 5) = 2numeric(10, 5) = 2,, @b@b varchar(2000)varchar(2000),, @c@c int int outputoutputasasSET NOCOUNT ONSET NOCOUNT ONSELECT TOP 5 title_id, type, price FROM titles SELECT TOP 5 title_id, type, price FROM titles

where type like @bwhere type like @bUPDATE titles set price = price * @aUPDATE titles set price = price * @a

where type like @bwhere type like @bselect @c = @@rowcountselect @c = @@rowcountSELECT TOP 5 title_id, type, price FROM titles SELECT TOP 5 title_id, type, price FROM titles

where type like @bwhere type like @b

----------------------------------------------------------------------------------------------------------declare @r declare @r intintexec exec p1 p1 .5, .5, '%cook', '%cook', @r@r outputoutputselect @rselect @r

Page 8: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

RETURNRETURNalter PROC p1alter PROC p1

@a @a numeric(10, 5) = 2numeric(10, 5) = 2,, @b@b varchar(2000)varchar(2000)asasSET NOCOUNT ONSET NOCOUNT ONSELECT TOP 1 * FROM titlesSELECT TOP 1 * FROM titles

where type like @bwhere type like @bUPDATE titles set price = price * UPDATE titles set price = price *

@a@awhere type like @bwhere type like @b

if @@error <> 0 if @@error <> 0 return(-1)return(-1)

else else beginbegin

SELECT TOP 1 * FROM titlesSELECT TOP 1 * FROM titleswhere type like @bwhere type like @b

SET NOCOUNT OFFSET NOCOUNT OFFreturn(0)return(0)

endend

declare @rtn intdeclare @rtn intEXEC @rtn = p1EXEC @rtn = p1

0.25 0.25, '%cook', '%cook'

select @rtnselect @rtn

Page 9: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

어떻게 수행되나 어떻게 수행되나 (( 일반 쿼일반 쿼리리 ))1. Parsing1. Parsing2. 2. 이름확인이름확인3. 3. 보안점검보안점검4. 4. 최적화최적화

((Optimize)Optimize)5. Compile5. Compile

재 실행 시 재 실행 시 ?? 같은 같은 context context

라면 그대로 사용 라면 그대로 사용 (( 극히 제한적인 극히 제한적인 경우경우 ))

그렇지 않다면 그렇지 않다면 11에서 에서 55 의 과정 의 과정 반복반복

Page 10: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

어떻게 수행되나 어떻게 수행되나 (SP)(SP) 만들 때만들 때

1. Parsing1. Parsing 2. 2. 이름확인이름확인 보안 점검보안 점검 (( 결과저장결과저장 ))

첫 실행첫 실행 4. 4. 최적화최적화

((Optimize)Optimize) 5. Compile5. Compile

재 실행 시 재 실행 시 ?? 그대로 사용그대로 사용 메모리에 없을때 메모리에 없을때

혹은 재 컴파일이 혹은 재 컴파일이 필요할때만 필요할때만 4, 54, 5의 과정 반복 의 과정 반복

Page 11: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

저장 프로시저 장점저장 프로시저 장점

편의성 편의성 ::매개변수매개변수 / return / result sets/ return / result sets

보안보안 네트웍 트래픽의 감소네트웍 트래픽의 감소 재사용 재사용 모듈화모듈화 성능 성능

Page 12: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

compile compile 과 성능과 성능dbcc freeproccachedbcc freeproccachegogouse pubsuse pubsgogo

exec sp_help sales exec sp_help sales ---- 첫번째첫번째exec sp_help sales exec sp_help sales ---- 두번째두번째exec sp_help sales exec sp_help sales ---- 세번째세번째exec sp_help sales exec sp_help sales with recompile with recompile

---- 강제 강제 recompilerecompile

use master use master gogosp_helptext sp_helpsp_helptext sp_help

Page 13: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

반드시 컴파일 해야 할 때반드시 컴파일 해야 할 때use tempdb gouse tempdb goDROP TABLE test goDROP TABLE test go

CREATE TABLE testCREATE TABLE test((

idid intint identityidentity,, c1 c1 char(100) default 'a'char(100) default 'a') go) go

SET NOCOUNT ONSET NOCOUNT ONdeclaredeclare @i@i intintset set @i = 0@i = 0

while @i < 5000while @i < 5000beginbegin

insert test default values insert test default values select @i = @i + 1select @i = @i + 1--select @i--select @i

endendoooo

CREATE NONCLUSTERED INDEX CREATE NONCLUSTERED INDEX NC_testNC_test

ON test (id)ON test (id)gogosp_helpindex testsp_helpindex test

CREATE PROC pTestCREATE PROC pTest@id@id intint

ASASSELECT * FROM test WHERE id < SELECT * FROM test WHERE id < @id@id

gogo

exec pTest 2exec pTest 2exec pTest 10exec pTest 10exec pTest 1000exec pTest 1000gogo

Page 14: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

반드시 컴파일 해야 할 때반드시 컴파일 해야 할 때 넌클러스터 인덱스가 있을 때넌클러스터 인덱스가 있을 때 (heap)(heap) 데이터 분포가 균일하지 않을 때데이터 분포가 균일하지 않을 때 매개변수로 인해 처리하는 데이터 양이 틀려질 매개변수로 인해 처리하는 데이터 양이 틀려질

때때

Page 15: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Solution: In Line EXECSolution: In Line EXECCREATE PROC pTest CREATE PROC pTest

@id@id intintASAS

DECLARE @sql varchar(200) DECLARE @sql varchar(200) …………SET @sql = ‘SELECT * FROM testSET @sql = ‘SELECT * FROM testWHERE id < ’ + cast (@id as varchar(20))WHERE id < ’ + cast (@id as varchar(20))EXEC (@sql)EXEC (@sql)......

!! 주의 주의 : : 권한 문제권한 문제 !!

Page 16: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

SP_EXECUTESQLSP_EXECUTESQL Similar to stored procedures, but… Similar to stored procedures, but…

Requires identification of parameters by applicationRequires identification of parameters by application Does not require persistent object managementDoes not require persistent object management

Syntax:Syntax:sp_executesql [@stmt =] sp_executesql [@stmt =] stmtstmt

[ [     {, [@params =] N'@    {, [@params =] N'@parameter_name  data_type parameter_name  data_type [,...[,...nn]' } ]' }     {, [@    {, [@param1param1 =] ' =] 'value1value1' [,...' [,...nn] }] }]]

Repeated calls with the same @stmt use cached plan Repeated calls with the same @stmt use cached plan (with the new parameter values specified)(with the new parameter values specified)

Page 17: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

SP_EXECUTESQLSP_EXECUTESQL Example:Example:

Q#1: sp_executesql N'insert mytable Q#1: sp_executesql N'insert mytable values(@p)', N'@p float', 1.0values(@p)', N'@p float', 1.0

Q#2: sp_executesql N'insert mytable Q#2: sp_executesql N'insert mytable values(@p)', N'@p float’, 2.0values(@p)', N'@p float’, 2.0

Q#3: sp_executesql N'insert mytable Q#3: sp_executesql N'insert mytable values(@p)', N'@p float', 1.0values(@p)', N'@p float', 1.0

Q#2 and Q#3 use same cached plan as Q#1Q#2 and Q#3 use same cached plan as Q#1

ODBC and OLEDB expose functionality via ODBC and OLEDB expose functionality via SQLExecDirect and SQLExecDirect and ICommandWithParametersICommandWithParameters

Page 18: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Prepare/ExecutePrepare/Execute Similar to SP_EXECUTESQL Similar to SP_EXECUTESQL

Parameters are identified by the Parameters are identified by the applicationapplication

Does not require the full text of the batch to Does not require the full text of the batch to be sent on each execution. be sent on each execution.

Handle returned on prepare used to invoke Handle returned on prepare used to invoke batch at execution timebatch at execution time

Also usable via ODBC and OLEDB when Also usable via ODBC and OLEDB when cursors are involvedcursors are involved

Page 19: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Prepare/ExecutePrepare/Execute ODBC and OLEDB expose functionality via ODBC and OLEDB expose functionality via

SQLPrepare/SQLExecute and SQLPrepare/SQLExecute and ICommandPrepareICommandPrepare

Example:Example:SQLPrepare(hstmt1, (unsigned char *)"select OID SQLPrepare(hstmt1, (unsigned char *)"select OID

from Orders where CustID = ?", SQL_NTS); …from Orders where CustID = ?", SQL_NTS); …SQLBindParameter(hstmt1, 1, SQLBindParameter(hstmt1, 1,

SQL_PARAM_INPUT, SQL_C_CHAR, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, sizeof(szCustomerID), SQL_CHAR, sizeof(szCustomerID), 0, &szCustomerID, sizeof(szCustomerID), 0, &szCustomerID, sizeof(szCustomerID), NULL); …NULL); …

rc = SQLExecute(hstmt1); …rc = SQLExecute(hstmt1); …

Page 20: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

적은적은 Round-TripsRound-TripsSQL Server 2000 SQL Server 2000 개선 부분개선 부분

Prepare/Execute model:Prepare/Execute model: 모든 파라메터의 타입을 명시할 수 있음모든 파라메터의 타입을 명시할 수 있음 PreparePrepare 와 와 Execute Execute 간의 요청 사항 간의 요청 사항

없음없음 N N 번의 라운드트립은 번의 라운드트립은 N N 번의 수행을 번의 수행을

이야기 한다이야기 한다 .. 권고 사항 권고 사항 : : 항상 항상 Prepare/Execute Prepare/Execute

사용하자사용하자 !!

Page 21: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Prepare/Execute Round-TripsPrepare/Execute Round-Trips SQL SQL 서버서버 7.07.0 에서에서

7.0 7.0 ClientClient

SQL Server 7.0SQL Server 7.0

User CodeUser Code

Prep

are

Prep

are

Han

dle

Han

dle

Exec

ute

Res

pons

e

UnP

repa

reU

nPre

pare

Res

pons

eR

espo

nse

Prep

are

Prep

are

Han

dle

Han

dle

Exec

ute

Res

pons

e

UnP

repa

reU

nPre

pare

Res

pons

eR

espo

nse

Exec

ute

Res

pons

e

Exec

ute

Res

pons

e

Prep

are

Exec

ute

Exec

ute

UnP

repa

re

Prep

are

Exec

ute

Exec

ute

UnP

repa

re

… …

Page 22: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Prepare/Execute Round-TripsPrepare/Execute Round-Trips SQL SQL 서버서버 20002000 에서에서

2000 2000 ClientClient

SQL Server 2000SQL Server 2000

User CodeUser Code

Prep

are+

Exec

ute

Han

dle

+Res

pons

e

UnP

rep+

Prep

+Exe

c

New

Han

dle+

Res

pons

e

Exec

ute

Res

pons

e

Exec

ute

Res

pons

e

Prep

are

Exec

ute

Exec

ute

UnP

repa

re

Prep

are

Exec

ute

Exec

ute

UnP

repa

re

… …

Page 23: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Plan Sharing Between UsersPlan Sharing Between Users Maximizes effectiveness of caching Maximizes effectiveness of caching

mechanismsmechanisms

Sharing rules:Sharing rules: Avoid changing environment (SET or Avoid changing environment (SET or

database settings) in middle of database settings) in middle of application or connectionapplication or connection

Insure that batches/procedures don't Insure that batches/procedures don't require implicit resolution require implicit resolution

Except when absolutely necessaryExcept when absolutely necessary

Page 24: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Plan Sharing Between UsersPlan Sharing Between Users Example of implicit resolution:Example of implicit resolution:

Mary and Jane are two users in database DBMary and Jane are two users in database DB Both have objects named FOOBoth have objects named FOO For Mary, “select * from DB..FOO” means For Mary, “select * from DB..FOO” means

“select * from DB.Mary.FOO” “select * from DB.Mary.FOO” For Jane, it means “select * from DB.Jane.FOOFor Jane, it means “select * from DB.Jane.FOO If Jane is executing the query the query “select If Jane is executing the query the query “select

* from DB..FOO” an implicit resolution is * from DB..FOO” an implicit resolution is requiredrequired

A batch/procedure compiled by Mary with this A batch/procedure compiled by Mary with this query could not be used by anyone except Maryquery could not be used by anyone except Mary

Page 25: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

Inappropriate Plan SharingInappropriate Plan Sharing If optimal plan for a parameter value is If optimal plan for a parameter value is

not the same as the cached plan, not the same as the cached plan, optimal execution time optimal execution time will not be will not be achievedachieved This is why the server is "conservative" about This is why the server is "conservative" about

auto-parameterizationauto-parameterization Application takes responsibility for Application takes responsibility for

determining what to parameterizedetermining what to parameterize When using sp_executesql, prepare/execute, When using sp_executesql, prepare/execute,

and/or stored procsand/or stored procs

Page 26: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

그럼 뭘 써야하지그럼 뭘 써야하지 ??

Stored ProceduresStored Procedures Multiple applications are executing batchesMultiple applications are executing batches Parameters are knownParameters are known

Prepare/ExecutePrepare/Execute Multiple applications are executing batches Multiple applications are executing batches Parameters are knownParameters are known Single users will use batches againSingle users will use batches again

SP_EXECUTESQL or EXECSP_EXECUTESQL or EXEC Parameters are knownParameters are known Single users Single users maymay use batches again use batches again

Page 27: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

그럼 뭘 써야하지그럼 뭘 써야하지 ??

Auto-parameterizationAuto-parameterization Don’t design new applications to useDon’t design new applications to use Beneficial to existing applications which Beneficial to existing applications which

cannot be modifiedcannot be modified Ad-hoc cachingAd-hoc caching

Don’t design new applications to useDon’t design new applications to use Provides benefits in limited scenarios Provides benefits in limited scenarios

Page 28: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

권고 사항권고 사항

Insure all users execute in the same Insure all users execute in the same environmentenvironment

Avoid implicit resolutionsAvoid implicit resolutions Take advantage of plan sharingTake advantage of plan sharing Do not parameterize constants whose range Do not parameterize constants whose range

of values drastically affect optimizationof values drastically affect optimization 최대한 저장 프로시저를 사용한다최대한 저장 프로시저를 사용한다 Prepare/ExecutePrepare/Execute 를 사용한다를 사용한다 . . ((SQLExecute SQLExecute

대신대신 ))

Page 29: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

system procedure system procedure 만들기만들기 Master Master 에 저장 에 저장 + sp_ + sp_ 로 시작로 시작

어디서든 실행 가능어디서든 실행 가능 sp_lock / sp_who2 sp_lock / sp_who2 등을 개선시켜보자등을 개선시켜보자

blocking blocking 관계에 있는 것만 보여주기관계에 있는 것만 보여주기 모든 모든 table table 의 행의 행 / / 컬럼 수 세기컬럼 수 세기 , , 크기 구하기크기 구하기 tabletable 의 모든 의 모든 index index 나열나열

Page 30: SQL Server 2000 세미나 Stored Procedure 강사 : 정원혁

DebuggingDebugging