pirmdiena, 2011. gada 9. maijs

Kursoru deklarēšana (divos veidos)

Jau iepriekš esmu minējis, ka no kursoriem cenšos maksimāli izvairīties, tomēr ir gadījumi, kad tos var izmantot arī labu risinājumu veidošanai. Šajā rakstā pavisam vienkārša kursora (MSDN šeit un vēl šeit) izveidošana divos dažādos veidos.

Pirmais veids:
declare @x int
declare cur cursor for
        Select 2 Union Select 3

open cur                     
fetch next from cur into @x
while @@fetch_status = 0
begin
    print @x
    fetch next from cur into @x
end
close cur;
Deallocate cur;
Otrajā veidā kursors ir kā mainīgais:
declare @x int
declare @cur cursor

Set @cur = Cursor for
        Select 2 Union Select 3

open @cur
fetch next from @cur into @x
while @@fetch_status = 0
begin
    print @x
    fetch next from @cur into @x
end

close @cur;
Deallocate @cur;
Kam tas otrais veids vajadzīgs? Piemēram, lai padotu kursoru kā parametru procedūrai (MSDN).
Procedūra [2012-07-05 mainīts piemērs]:
Create Proc dbo.myProc
(
    @someValue int,
    @cur Cursor Varying Output
)
As
Begin
    declare @x int;
    Set @cur = Cursor for
        Select i From dbo.MyTable
        Where i < @someValue;
      
    open @cur
End
Izskatās tas, piemēram, tā:
create Table dbo.MyTable
(
    i int
);
Insert Into dbo.MyTable (i) values (1)
Insert Into dbo.MyTable (i) values (2)
Insert Into dbo.MyTable (i) values (3)
Insert Into dbo.MyTable (i) values (4)
Go
Set NoCount ON;
Go
Create Proc dbo.myProc
(
    @someValue int,
    @cur Cursor Varying Output
)
As
Begin
    declare @x int;

    Set @cur = Cursor for
        Select i From dbo.MyTable
        Where i < @someValue;
      
    open @cur
End
Go
-- Use of proc
declare @cur cursor;
declare @x int;
Exec dbo.myProc 3, @cur output

fetch next from @cur into @x
while @@fetch_status = 0
begin
    print 'value: ' + cast(@x as varchar)
    fetch next from @cur into @x
end

close @cur;
Deallocate @cur;

Go
--Cleanup
Drop Proc dbo.myProc
Drop Table dbo.MyTable

1 komentārs: