如何在oracle存储过程中获取游标数据

时间:2014-07-11 12:16:59

标签: oracle

create or replace
PROCEDURE get_new
AS
    CUST_ID varchar2(100);
    ROUTERNAME_N VARCHAR2(100); 
BEGIN
    CURSOR c1 IS
    SELECT TRAFFIC_CUST_ID,ROUTERNAME INTO CUST_ID,ROUTERNAME_N
    FROM INTERFACE_ATTLAS
    WHERE rownum > 3;

    my_ename INTERFACE_ATTLAS.TRAFFIC_CUST_ID%TYPE;
    my_salary INTERFACE_ATTLAS.ROUTERNAME%TYPE;

    LOOP
        FETCH c1 INTO my_ename;
        FETCH c1 INTO my_salary;
        EXIT WHEN c1%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(my_ename);
    end loop;
end;

我是oracle和存储过程的新手。我试图使用游标提取获取行,并收到以下错误:

PLS-00103: Encountered the symbol "C1" when expecting one of the following:
:= . ( @ % ;

4 个答案:

答案 0 :(得分:4)

像这样改写:

create or replace
PROCEDURE get_new
AS
    my_ename INTERFACE_ATTLAS.TRAFFIC_CUST_ID%TYPE;
    my_salary INTERFACE_ATTLAS.ROUTERNAME%TYPE;
    CURSOR c1 IS
    SELECT TRAFFIC_CUST_ID,ROUTERNAME
    FROM INTERFACE_ATTLAS
    WHERE rownum > 3;
BEGIN
  open c1;    
    LOOP
        FETCH c1 INTO my_ename, my_salary;
        EXIT WHEN c1%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(my_ename);
    end loop;
  close c1;
end;

不要忘记打开和关闭游标。由于rownum > 3;您想要输入rownum < 3;,不打印,所以它始终不打印任何内容,

答案 1 :(得分:0)

您应该在专用部分(即my_ename之前)声明光标和变量my_salaryBEGIN,然后打开光标:

IS
    CUST_ID varchar2(100);
    ROUTERNAME_N VARCHAR2(100);
    C1 sys_refcursor;
    my_ename INTERFACE_ATTLAS.TRAFFIC_CUST_ID%TYPE;
    my_salary INTERFACE_ATTLAS.ROUTERNAME%TYPE;
BEGIN
    OPEN C1 for
    SELECT ...

答案 2 :(得分:0)

你必须在BEGIN之前声明Cursor。您将在游标声明中不使用INTO子句。然后你必须打开光标。然后你会FETCH INTO my_ename, my_salary,而不是一个接一个(你获取行,而不是列)。 WHERE rownum > 3不返回任何行。由于你不想要第一行,你也永远不会得到第二,第三和第四行。

你可以使用一个更容易处理的隐式游标(不需要明确地打开,获取和关闭):

BEGIN
  FOR rec IN
  (
    select traffic_cust_id, routername 
    from interface_attlas
    where rownum <= 3
  ) LOOP
     DBMS_OUTPUT.PUT_LINE(rec.traffic_cust_id || ': ' || rec.salary);
  END LOOP;
END;

答案 3 :(得分:0)

create or replace
PROCEDURE get_new
AS
    CUST_ID varchar2(100);
    ROUTERNAME_N VARCHAR2(100); 
BEGIN
    CURSOR c1 IS
    SELECT TRAFFIC_CUST_ID,ROUTERNAME INTO CUST_ID,ROUTERNAME_N
    FROM INTERFACE_ATTLAS
    WHERE rownum > 3;

    my_ename INTERFACE_ATTLAS.TRAFFIC_CUST_ID%TYPE;
    my_salary INTERFACE_ATTLAS.ROUTERNAME%TYPE;

    LOOP
        FETCH c1 INTO my_ename;
        FETCH c1 INTO my_salary;
        EXIT WHEN c1%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(my_ename);
    end loop;
end;

光标应该在声明部分声明。然后必须在开始结束部分打开。在声明部分中,您无法为变量赋值。当您获取值时,您无法随机选择值格式光标,

修改后的代码:

create or replace
PROCEDURE get_new
AS
   no mean --CUST_ID varchar2(100);
  no means -- ROUTERNAME_N VARCHAR2(100); 

    CURSOR c1 IS
    SELECT deptno,job
    FROM emp;

    my_ename emp.deptno%TYPE;
    my_salary emp.job%TYPE;

BEGIN
    open c1;

    LOOP

       fetch c1 into my_ename,my_salary;
       -- FETCH c1 INTO my_ename;
        --FETCH c1 INTO my_salary;
        EXIT WHEN c1%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(my_ename);
    end loop;
end;

execute get_new.