PL / SQL的新手,我试图弄清楚这个问题并加以解决,但是很茫然。希望你们的专业知识和指导。
这是我的代码,希望您能看到我要去的地方。我知道我需要一个游标或一个循环,也许才能使其正常工作。但是,我不确定放置在哪里以及如何使用它。
感谢您的帮助。
create or replace
procedure customer_credit(cust_ID IN NUMBER) AS
credit_num NUMBER;
begin
select CUSTOMER_ID, CREDIT_LIMIT from OE.CUSTOMERS WHERE CUSTOMER_ID=cust_ID;
dbms_output.put_line('Credit Limit = ', || credit_num);
end;
/
exec customer_credit(145);
答案 0 :(得分:2)
有多种选择。一种是使用SELECT ... INTO:
create or replace
procedure customer_credit(cust_ID IN NUMBER) AS
credit_num NUMBER;
begin
select CREDIT_LIMIT
into credit_num
from OE.CUSTOMERS WHERE CUSTOMER_ID=cust_ID;
dbms_output.put_line('Credit Limit = ', || credit_num);
end;
未找到该行,将生成异常。您可以通过添加异常处理程序或使用显式的open / fetch / close游标方法来解决此问题。如果要从sqlplus执行该过程,则需要先调用
set serveroutput on
查看dbms_output的结果。
答案 1 :(得分:1)
如果要返回该值,最好将其定义为FUNCTION,然后在代码中调用该函数。这将允许您在PL / SQL过程和SELECT语句中使用它。您还应该使用异常处理程序来处理情况。我已修改您的示例以说明所需的更改:
create or replace
function customer_credit(cust_ID IN NUMBER)
return number
IS
credit_num NUMBER;
begin
select CREDIT_LIMIT
into credit_num
from OE.CUSTOMERS WHERE CUSTOMER_ID=cust_ID;
dbms_output.put_line('Credit Limit = ', || credit_num);
return(credit_num);
exception
when NO_DATA_FOUND then
return(0);
end;
/
select customer_credit(145) from dual;
希望有帮助。
答案 2 :(得分:0)
我相信您的过程已编译并带有警告,您已声明变量credit_num,但未将任何值传递给该变量。(因此,如果该变量没有任何内容,它将如何返回Something。)>
如果要从表中获取CREDIT_LIMIT,则应使用Select Into编写代码,例如:-
select CREDIT_LIMIT
into credit_num
from OE.CUSTOMERS
where CUSTOMER_ID=cust_id;
只需更改您的select语句,您就可以使用程序了。
答案 3 :(得分:0)
您可以使用Cursor
,或者:
create or replace procedure customer_credit( cust_ID IN NUMBER) as
begin
for c in ( select CUSTOMER_ID, CREDIT_LIMIT from CUSTOMERS WHERE CUSTOMER_ID=cust_ID )
loop
dbms_output.put_line('Credit Limit = '|| c.CREDIT_LIMIT);
end loop;
end;
顺便说一句,应该在comma
子句中删除错字(dbms_output.put_line()
)。如@OldProgrammer所述,应发出set serveroutput on
以查看结果。
答案 4 :(得分:0)
这将起作用:
create or replace
procedure customer_credit(cust_ID IN NUMBER) AS
credit_num NUMBER;
begin
select CREDIT_LIMIT into credit_num from OE.CUSTOMERS WHERE CUSTOMER_ID=cust_ID;
dbms_output.put_line('Credit Limit = ', || credit_num);
end;
/
exec customer_credit(145);