这是我写的程序:
set serveroutput on;
declare
b empl.name1%type;
r varchar; --can i change this to r empl.designation%type; ?
begin
r:=&designation; --getting input for the designation
dbms_output.put_line('hello'); --random output to check for errors
select name1 into b from empl where designation=r; --i want all the names from the table
dbms_output.put_line('name'||b); --employee where designation is as entered
dbms_output.put_line(' closed'); --by user,should i loop this statement?
end;
Run Code Online (Sandbox Code Playgroud)
当我输入指定为'a'(已在表中输入)时,我收到错误
identifier 'a' is not declared.那是什么意思?select语句一次只占一行吗?所以,如果我循环它将获得所有行?或者我应该使用光标?为什么SQL Developer不接受%rowtype?
我将程序改为:
set serveroutput on;
declare
cursor cempl is select name1,designation from empl;
b empl.name1%type;
des empl.designation%type;
r empl.designation%type;
begin
r:='meow';
dbms_output.put_line('hello');
open cempl;
if cempl%ISOPEN then
loop
fetch cempl into b,des;
if des=r then
dbms_output.put_line('name'||b);
end if;
exit when cempl%notfound;
end loop;
close cempl;
dbms_output.put_line(' closed');
end if;
end;
Run Code Online (Sandbox Code Playgroud)
每当我得到一个类似的输入r:=&r并想象我输入'a'时,它必须声明标识符'a',但它是表中的值!为什么要声明它,但如果它在程序中给出如上所述它不会给出错误.相反,它重复最后一行两次!
这里有几个问题要回答:
'Identifier not found'错误: &designation是一个SQL*Plus替换变量.输入值时&designation,SQL*Plus将替换&designation为您输入的文本.所以,如果你输入vaue a,就行了
r:=&designation;
Run Code Online (Sandbox Code Playgroud)
变
r:=a;
Run Code Online (Sandbox Code Playgroud)
出现错误是因为Oracle不知道任何调用的内容a.您尚未声明一个名为的变量a,并且没有过程或函数或其他任何可以找到的名称a.如果你想要最终结果r:='a';,你需要写r:='&designation';
SELECT ... INTO ...仅在查询返回一行时才有效.如果没有返回任何行,则会出现no data found错误,如果返回多行,则会出现too many rows错误.只有SELECT ... INTO ...在您知道只有一个结果时才应该使用.如果可能有多个结果,则应使用游标.
'为什么SQL Developer不接受%rowtype'?应该这样做 - 你能想出一个给你带来麻烦的例子吗?
在第二个示例中,您将重复最后一行,因为在光标无法找到更多行之后您没有立即退出循环.您应该将exit when线移动到线的正下方fetch.