본문 바로가기

데이터베이스

SQL Server CURSOR

# cursor

select문을 실행하고 나면 result set을 반환받는다. cursor는 이렇게 반환받은 result set의 각각에 행을 다룰 수 있게 도와 준다. 

 

# cursor life cycle 

cursor life cycle 

# Declare cursor

 

Declare cursor이름 Cursor -- Declare 키워드를 쓴다. -> cursor에 이름 쓴다.  -> 데이터타입이 Cursor라 쓴다.

    for select statement;  -- select 문을 사용하여 cursor로 다룰 result set을 정의한다.

 

# select statement를 실행시키고 cursor로 result set을 집어넣는다.

 

Open cursor_name  

 

# cursor로 부터 행을 하나 꺼내어 하나 이상의 변수에 집어넣는다.

 

Fetch Next From Cursor Into 변수1, 변수2...

 

# FETCHSTATUS 

 

@@FETCHSTATUS는 함수다. Cursor를 대상으로 수행한 Fetch문의 상태를 반환한다. 

 

만약 반환값이 0이면 수행한 Fetch문이 성공이다. while을 사용하여 cursor로 부터 모든행을 계속 다룰 수 있다.

 

while @@FETCH_STATUS = 0

    begin

        Fetch Next From cursor_name

    end 

 

# Close

while 블록을 끝나고 open과 반대의 close를 해준다. 

 

Close cursor_name

 

# Deallocate 

마지막으로 cusor를 해제한다. 

 

Deallocate cursor_name

 

# Sql Server cursor예

 

Declare @id int,
           @name varchar(50);

Declare cursor_author Cursor
for select id, author_name
from Author
;

open cursor_author;

fetch next from cursor_author 
into @id, @name
;

while @@FETCH_STATUS = 0
begin
print cast( @id as varchar) + @name
Fetch next from cursor_author
into @id, @name
;
end

close cursor_author

deallocate cursor_author;

 

 

 

 

 

'데이터베이스' 카테고리의 다른 글

SHOWPLAN_TEXT  (0) 2020.06.16
SQL Server DATEDIFF, DATEADD , DatePart  (0) 2020.06.15
Cross Apply와 Outer Apply 차이  (0) 2020.06.12
테이블 변수(SQL Server Table Variables)  (0) 2020.06.11
임시 테이블 Temporary Tables  (0) 2020.06.10