I have a cursor c2, with one column 'note', containing numbers. I want to check, whether the column contains 5 and change my local variable if so.

this:

CREATE OR REPLACE PROCEDURE proc

IS
result varchar(50);

cursor c2 is
SELECT  note
FROM    student;    

BEGIN

IF c2.note IN(5) THEN
result := 'contains 5';

DBMS_OUTPUT.PUT_LINE(result);

END;
/

doesnt work.

please help!

有帮助吗?

解决方案 2

You have too loop over the records/rows returned in the cursor; you can't refer to the cursor itself like that:

CREATE OR REPLACE PROCEDURE proc
IS
    result varchar(50);

    cursor c2 is
        SELECT  note
        FROM    student;    
BEGIN
    FOR r2 IN c2 LOOP
        IF r2.note = 5 THEN -- IN would also work but doesn't add anything
            result := 'contains 5';
        END IF;
    END LOOP;

    DBMS_OUTPUT.PUT_LINE(result);
END;
/

But if you're just testing for the existence of any record with value 5 then you don't need a cursor:

CREATE OR REPLACE PROCEDURE proc
IS
    result varchar(50);
BEGIN
    SELECT max('contains 5')
    INTO result
    FROM student
    WHERE note = 5;

    DBMS_OUTPUT.PUT_LINE(result);
END;
/

If there are any rows with five you'll get the 'contains 5' string; if not you'll get null. The max() stops an exception being thrown if there are either zero or more than one matching records in the table.

其他提示

In your code, you're declaring a cursor but you are never opening it and never fetching data from it. You'd need, presumably, some sort of loop to iterate through the rows that the cursor returned. You'll either need to explicitly or implicitly declare a record into which each particular row is fetched. One option to do that is something like

CREATE OR REPLACE PROCEDURE proc
IS
  result varchar(50);

  cursor c2 is
    SELECT  note
      FROM  student;    
BEGIN
  FOR rec IN c2
  LOOP
    IF rec.note IN(5) THEN
      result := 'contains 5';
      DBMS_OUTPUT.PUT_LINE(result);
    END IF;

  END LOOP;
END;
/

Note that you also have to have an END IF that corresponds to your IF statement. Naming a cursor c2 is also generally a bad idea-- your variables really ought to be named meaningfully.

You are missing an END IF and need to LOOP over the cursor. The procedure name is included in the final END.

But using IN should work. Like this:

CREATE OR REPLACE PROCEDURE proc    
IS
  result varchar(50);

  cursor c2 is
  SELECT  note
  FROM    student;    

BEGIN
  FOR rec in c2
  LOOP 
    IF rec.note IN (5) THEN
      result := 'contains 5';
    END IF;   
  END LOOP;

  DBMS_OUTPUT.PUT_LINE(result);

END proc;
/
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top