在Pro*C中的滚动游标可以方便的获得当前记录的前面一条,后面一条,以及第一条、最后一条。
很多开发人员一般采用如下的方法,循环FETCH 直到最后一条。
while (1)
{
fetch 游标名 into 变量列表;
if (sqlca.sqlcode=1403) then break;
}
如果使用滚动游标,会更加方便获得最后一条。
下面给出一个简单的例子
SQL> SELECT EMPNO,ENAME FROM EMP ORDER BY EMPNO;
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
已选择14行。
/home/cpicsrv/yansp > cat test.pc
#include
#include
exec sql include sqlca;
main()
{
exec sql begin declare section;
char *username="scott";
char *password="tiger";
char *dbserver="10.223.18.116/yansp";
char ename[10];
int empno;
exec sql end declare section;
exec sql whenever sqlerror stop;
exec sql declare mycursor scroll cursor
for select empno,ename from emp order by empno;
exec sql connect :username identified by :password using :dbserver;
if (sqlca.sqlcode!=0)
{
printf("Connect to database failed!\n");
printf("Error message is %s.\n",sqlca.sqlerrm.sqlerrmc);
}
exec sql open mycursor;
exec sql fetch first mycursor into :empno,:ename; /*取游标中第一条记录*/
printf("First:empno=[%d],ename=[%s]\n",empno,ename);
exec sql fetch next mycursor into :empno,:ename; /*取游标中下一条记录*/
printf("Next:empno=[%d],ename=[%s]\n",empno,ename);
exec sql fetch prior mycursor into :empno,:ename; /*取游标中上一条记录*/
printf("Prior:empno=[%d],ename=[%s]\n",empno,ename);
exec sql fetch last mycursor into :empno,:ename; /*取游标中最后一条记录*/
printf("Last:empno=[%d],ename=[%s]\n",empno,ename);
exec sql close mycursor;
exec sql commit work release;
}
/home/cpicsrv/yansp > proc parse=none test.pc
Pro*C/C++: Release 10.2.0.1.0 - Production on Tue Jan 10 18:08:55 2012
Copyright (c) 1982, 2005, Oracle. All rights reserved.
System default option values taken from: /home/oracle/oracle/product/10.2.0/client_1/precomp/admin/pcscfg.cfg
/home/cpicsrv/yansp > gcc $ORACLE_HOME/lib/libclntsh.so test.c -o test
/home/cpicsrv/yansp > ./test
First:empno=[7369],ename=[SMITH ]
Next:empno=[7499],ename=[ALLEN ]
Prior:empno=[7369],ename=[SMITH ]
Last:empno=[7934],ename=[MILLER ]
阅读(2603) | 评论(0) | 转发(1) |