2025년 4월 8일 화요일

MSSQL - Cursor vs Temp Table


#테이블 변수사용의 예

use pubs
go

declare @tmptable table
(
    nid int identity(1,1) not null,
    title varchar(80) not null
) -- 테이블 변수 선언

insert @tmptable(title)
select title from titles -- titles테이블의 title을 테이블변수에 삽입(루프생성을 위해)

declare @print varchar(5000) -- print변수 선언

declare @i int, @maxno int, @title varchar(80)     -- 루프변수 선언
select @i=1, @maxno=max(nid) from @tmptable   -- 루프변수 초기화
while @i<=@maxno -- 루프문
begin
    select @title=title from @tmptable where nid=@i -- 커서의 fetch into해당
    if(@i = 1)
    begin
        set @print = @title
    end
    else
    begin
        set @print = @print + ' | ' + @title
    end
    set @i=@i+1
end 
print @print


#커서사용의 예

declare @title varchar(100)
declare @print varchar(5000)
set @print = ''
declare c_cursor CURSOR FOR
   select title from titles
for read only
open c_cursor
fetch next from c_cursor
into @title
while(@@fetch_status <> -1)
   begin
       if(@@fetch_status <> -2)
       begin
           if(@print = '')
           begin
              set @print = @title
           end
           else
           begin
              set @print = @print + ' | ' + @title
           end
       end
  fetch next from c_cursor
  into @title
end
close c_cursor
deallocate c_cursor
print @print


출처 : https://using.tistory.com/14



MSSQL - Cursor vs Temp Table

#테이블 변수사용의 예 use pubs go declare @tmptable table (     nid int identity(1,1) not null,     title varchar (80) not null ) -- 테이블 변수 선언 inse...