可以动态传递参数吗?
例如:
create or replace procedure getRec
as
cursor get(nameToGet varchar2) is select * from test where name = nameToGet;
rec test%rowtype;
begin
for rec in get('sam') loop
if get%notfound then
dbms_output.put_line('No record found');
else
dbms_output.put_line('Name : ' || ' ' || rec.name ||' ::: ' || 'Address : '
|| rec.address);
end if;
end loop;
end;
但这是硬编码的('nameToGet'的值)。如何动态地将值传递给游标(如果可能)? 当然,我们可以使用像
这样的参数化程序来做到这一点create or replace procedure getRec(nameToGet IN varchar2)
,光标就像
cursor get is select * from test where name = nameToGet;
但我想创建一个参数化游标并动态地将值传递给游标。
另一方面,当找不到记录时,dbms_output('找不到记录')不会执行。任何人都可以纠正这些代码吗?
答案 0 :(得分:0)
如果需要,可以将procedure参数传递给游标:
create or replace procedure getRec(nameToGet IN varchar2)
as
cursor get(nameToGet varchar2) is select * from test where name = nameToGet;
begin
for rec in get(nameToGet) loop
...
如果你给参数赋予不同的名称,你可能会发现它不那么令人困惑,例如:有一个程序参数名称约定以' p'开头。前缀,以' c'开头的游标参数前缀,或其他什么。
我已经取消了rec
变量,因为它从未使用过; rec
中的for rec in ...
是一个完全不相关的变量。
所有dbms_output
逻辑都在光标内循环,因此只会在循环内进行评估 - 即有数据时。如果你想使用这个循环结构,你可以使用一个标志来记录你是否已进入循环,例如:
create or replace procedure getRec(pNameToGet IN varchar2)
as
cursor get(cNameToGet varchar2) is
select * from test where name = cNameToGet;
lDataSeen boolean := false;
begin
for rec in get(pNameToGet) loop
lDataSeen := true;
dbms_output.put_line('Name : ' || ' ' || rec.name ||' ::: ' || 'Address : '
|| rec.address);
end loop;
if !lDataSeen then
dbms_output.put_line('No record found');
end if;
end;