目的:操作多行多列时,逐行或随机处理数据。
1。定义游标
EXEC SQL DECLARE emp_cursor CURSOR FOR
select empno,ename,sal from emp where deptno=10;
2. 打开游标
EXEC SQL OPEN emp_cursor ;
(Open cursor: put the select results into a memory place,
and the cursor pointer points to the first row data.)
3. 提取数据 fetch into
EXEC SQL FETCH emp_cursor INTO :empnum,:name:salary;
/** 在此处理数据处理**/
(After fetch, cursor pointer moves down one line. Use loop for
multiple rows)
4. EXEC SQL CLOSE emp_cursor;
|
//普通游标,向下读
EXEC SQL FETCH dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s ", deptno, dname, loc );
//演示滚动游标查询数据
//查询最后一条数据
EXEC SQL FETCH LAST dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );
//查询第一条数据
EXEC SQL FETCH FIRST dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );
//查询第3条数据
EXEC SQL FETCH ABSOLUTE 3 dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );
//查询相对第3条数据 也就是第6条
EXEC SQL FETCH RELATIVE 3 dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );
//查询下一条
EXEC SQL FETCH NEXT dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );
//查询前一条
EXEC SQL FETCH PRIOR dept_cursor INTO :deptno, :dname:dname_ind, :loc:loc_ind;
//printf("条目数:%d\t", sqlca.sqlerrd[2]);
printf("%d\t %s\t %s \n", deptno, dname, loc );