Oracle/PLSQL: Creating Functions

None.gif In Oracle, you can create your own functions.
None.gif
None.gifThe syntax for a function is:
None.gif
None.gifCREATE [OR REPLACE] FUNCTION function_name
None.gif    [ (parameter [,parameter]) ]
None.gif    RETURN return_datatype
None.gifIS | AS
None.gif    [declaration_section]
None.gifBEGIN
None.gif    executable_section
None.gif[EXCEPTION
None.gif    exception_section]
None.gifEND [function_name];
None.gif
None.gif
None.gif
None.gifWhen you create a procedure or function, you may define parameters. There are three types of parameters that can be declared:
None.gif
None.gifIN - The parameter can be referenced by the procedure or function. The value of the parameter can not be overwritten by the procedure or function. 
None.gifOUT - The parameter can not be referenced by the procedure or function, but the value of the parameter can be overwritten by the procedure or function. 
None.gifIN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can be overwritten by the procedure or function. 
None.gif
None.gif
None.gifThe following is a simple example of a function: 
None.gif
None.gifCREATE OR REPLACE Function FindCourse
None.gif   ( name_in IN varchar2 )
None.gif   RETURN number
None.gifIS
None.gif    cnumber number;
None.gif
None.gif    cursor c1 is
None.gif    select course_number
None.gif      from courses_tbl
None.gif      where course_name = name_in;
None.gif
None.gifBEGIN
None.gif
None.gifopen c1;
None.giffetch c1 into cnumber;
None.gif
None.gifif c1%notfound then
None.gif     cnumber := 9999;
None.gifend if;
None.gif
None.gifclose c1;
None.gif
None.gifRETURN cnumber;
None.gif
None.gifEXCEPTION
None.gifWHEN OTHERS THEN
None.gif      raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
None.gifEND;
None.gif
None.gifThis function is called FindCourse. It has one parameter called name_in and it returns a number. The function will return the course number if it finds a match based on course name. Otherwise, it returns a 99999.
None.gif
None.gif
None.gif
None.gifYou could then reference your new function in an SQL statement as follows: 
None.gif
None.gifselect course_name, FindCourse(course_name) as course_id
None.giffrom courses
None.gifwhere subject = 'Mathematics'; 
None.gif

转载于:https://www.cnblogs.com/timsoft/articles/412693.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值