Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CURSOR function equivalent in SQL Server

I would like to ask regarding a code equivalent in SQL Server

I'm working on a project wherein we will be converting unix batches to windows batches due to database migration. Since I'm on shell scripts and oracle stuffs, I'm having a hard time working on windows side.

My question is about the CURSOR that oracle sql uses.

Can someone help me convert the following sample query below

sampleanimal.sql:

declare cursor getGM is
select dog as d, cat as c, fish as f
  from animals

begin
  for dr in getGM loop

    UPDATE zoo
      SET dogs = dr.d
          cats = dr.c
          fishes = dr.f
      ;

  end loop;
end;
/

commit;

quit; 
like image 842
Gemudesu Avatar asked Nov 19 '25 21:11

Gemudesu


2 Answers

There can be more efficient or easy way, I just wrote without test

DECLARE @d nvarchar(10);
DECLARE @c nvarchar(10);
DECLARE @f nvarchar(10);

DECLARE getGM CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR
select dog as d, cat as c, fish as f from animals

OPEN getGM
FETCH NEXT FROM getGM INTO @d, @c, @f

WHILE @@FETCH_STATUS = 0
Begin
UPDATE zoo
      SET dogs = @d
          cats = @c
          fishes = @f

FETCH NEXT FROM getGM INTO @d, @c, @f
End

CLOSE getGM
DEALLOCATE getGM

you can check examples from msdn

like image 79
Gökhan Girgin Avatar answered Nov 21 '25 10:11

Gökhan Girgin


Really, you not need to use cursor in this case. Try something like this -

UPDATE z
SET 
      dogs = a.dog
    , cats = a.cat
    , fishes = a.fish
FROM zoo z
JOIN animals a ON z.id = a.id
like image 42
Devart Avatar answered Nov 21 '25 12:11

Devart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!