sql笔记(3)游标

create database Book

create table booker(
bookno int primary key not null,
bookname varchar(50) not null,
bookprice float not null,
bookcount int not null,
bookwriter varchar(50) not null
)

insert into booker values(1,'王晓京',2000,25,'李春春')
insert into booker values(2,'王晓京2',2000,25,'李春春2')
insert into booker values(3,'王晓京3',2000,25,'李春春3')

select *from booker
-------全局变量------------------------
select @@version  --查看sql的版本号
select @@error    --返回最后执行的 Transact-SQL 语句的错误代码。
-------变量的声明--------------------------------------------------
declare @变量名 int--声明
set @变量名=10     --赋值
select @变量名     --输出变量值 以上三步同时执行有效

if(1=1)
      begin
select *from booker
      end


------------------------------------------------游标-------

--------------------------.1声明游标   语法: declare 游标名 cursor for select_statement
declare cursor_name cursor
for select bookno,bookname from booker where bookcount=25
--------------------------.2打开游标   语法: open    游标名
open cursor_name
--------------------------.3提取游标值 语法:fetch next from 游标名 while(@@fetch_status=0)  begin fetch next from 游标名 end
fetch next from cursor_name while(@@fetch_status=0)--返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
--  返回值      描述
--   0   FETCH语句成功。
--  -1   FETCH语句失败或此行不在结果集中。
--  -2          被提取的行不存在。
                
begin
fetch next from cursor_name
end
--------------------------.4关闭游标 close 游标名
close cursor_name
--------------------------.5删除游标 deallocate  游标名
deallocate cursor_name

原文地址:https://www.cnblogs.com/top100/p/2092746.html