简体   繁体   中英

Declaring cursor in a PL/SQL stored procedure

printf('local_time_greeting');

Having some trouble getting a stored procedure to run with SQL Developer. Below is an example patterned exactly like the first few lines, with variable names changed for security reasons.

CREATE OR REPLACE PROCEDURE redacted ( an_in_variable IN VARCHAR ) AS
    these VARCHAR;
    variables VARCHAR;
    don_apostrophe_t INT;
    matter INT;
BEGIN

DECLARE cursor_giving_me_trouble CURSOR FOR
SELECT something FROM db.table WHERE condition_1 = condition_2;
...

In the editor the SELECT word is red-wavy-lined, and when I try to run the code the output returns

PLS-00103: Encountered symbol "FOR" when expecting one of the following     := . ( @ % ; not null range default character

Any ideas?

You need to use IS rather than FOR , but you have the terms of the definition in the wrong order as well:

DECLARE
  CURSOR cursor_giving_me_trouble IS
    SELECT something FROM db.table WHERE condition_1 = condition_2;

db<>fiddle which still errors because of the illegal object names in your obfuscated code, but not from the syntax; and a more complete example .

It's also possible you're trying to use the construct:

FOR cursor_giving_me_trouble IN (
    SELECT something FROM db.table WHERE condition_1 = condition_2
) LOOP
...

rather than a sub-block (a new declare, followed by begin/end) with references only to cursor within that. db<>fiddle .

To get you started:

create or replace procedure redacted
    ( an_in_variable in varchar2 )
as
    these varchar2(123);
    variables varchar2(456);
    don_apostrophe_t integer;
    matter integer;
    cursor cursor_giving_me_trouble is
        select 'Welcome to PL/SQL' as whatever from dual where 1=1;
begin
    for r in cursor_giving_me_trouble loop
        dbms_output.put_line(r.whatever);
    end loop;
end;

However, you often don't need a separate cursor definition as there is this compact syntax:

create or replace procedure redacted
    ( an_in_variable in varchar2 )
as
    these varchar2(123);
    variables varchar2(456);
    don_apostrophe_t integer;
    matter integer;
begin
    for r in (
        select 'Welcome to PL/SQL' as whatever from dual where 1=1
    )
    loop
        dbms_output.put_line(r.whatever);
    end loop;
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM