test数据库有表如下;
创建一个存储过程,输出姓名和电话;
CREATE PROCEDURE printname
AS
BEGIN
DECLARE @sName varchar(20), @phone varchar(20)
DECLARE cursor1 CURSOR FOR --定义游标
SELECT name,phonenumber from t_student
OPEN cursor1
FETCH NEXT FROM cursor1 INTO @sName,@phone
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT '姓名:'+@sName+' '+'电话:'+@phone
FETCH NEXT FROM cursor1 INTO @sName,@phone
END
CLOSE cursor1
DEALLOCATE cursor1
END
运行如下;
CREATE PROCEDURE printname
AS
BEGIN
......
END
这是创建存储过程的基本语法;
DECLARE @sName varchar(20), @phone varchar(20),定义变量;
DECLARE cursor1 CURSOR FOR --定义游标
SELECT name,phonenumber from t_student
定义游标,游标名为cursor1,把FOR后面sql语句获取的数据放入游标;
FETCH NEXT FROM cursor1 INTO @sName,@phone
从游标提取一条记录的对应字段值放入变量;
print,打印;
OPEN cursor1
CLOSE cursor1
DEALLOCATE cursor1
打开,关闭,销毁游标;
@@fetch_status是MSSQL的一个全局变量,返回类型integer,其值有以下三种,
0 FETCH 语句成功
-1 FETCH 语句失败或此行不在结果集中
-2 被提取的行不存在