Search notes:

SQL Server: cursors

A cursor is, like variables, declared with the declare statement.
However, unlike other variables, the name of the cursor is not prefixed with an at sign (@).
Also, the cursors need to be declared separately from other variables, that is, each of them needs their own declare statement.
set nocount on

create table tq84_tab(col_1 int, col_2 varchar(10));

insert into tq84_tab values (1, 'one'  );
insert into tq84_tab values (2, 'two'  );
insert into tq84_tab values (3, 'three');
go

declare
   cur_tq84_tab cursor for
       select *
       from
          tq84_tab
       where
          col_2 like 't%'
       order by
          col_2;
declare
   @val_1       integer,
   @val_2       varchar(10);

open cur_tq84_tab;

fetch next from cur_tq84_tab into @val_1, @val_2;
while @@fetch_status = 0 begin
      print('Fetched a record:'           );
      print('   col_1 = ' + str(@val_1, 1));
      print('   col_2 = ' +     @val_2    );

      fetch next from cur_tq84_tab into @val_1, @val_2;
end;

close      cur_tq84_tab;
deallocate cur_tq84_tab;
go

drop table tq84_tab;
go
Github repository about-MSSQL, path: /t-sql/cursors/simple.sql

See also

@@fetch_status
T-SQL
SQL Standard feature F431 (read-only scrollable cursor)

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1737533652, '3.147.195.28', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/SQL-Server/T-SQL/cursors/index(91): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78