pl/sql基础知识—函数快速入门

n  函数

函数用于返回特定的数据,当建立函数式,在函数头部必须包含return子句,而在函数体内必须包含return语句返回的数据,我们可以使用create function来建立函数,实际案例:

基本语法:

create function 函数名(参数1,参数2…)

return 数据类型  is

//定义变量;

begin

//执行语句;

end;

 

案例:请编写一个函数,可以接收用户名并返回该用户的年薪。

SQL> create or replace function fun1(v_in_ename varchar2)

  2  return number is

  3  v_annual_sal number;

  4  begin

  5    select (sal+nvl(comm,0))*13 into v_annual_sal from emp where ename=v_in_ename;

  6    return v_annual_sal;

  7  end;

  8  /

Function created

 

SQL> select fun1('SMITH') from dual;

FUN1('SMITH')

-------------

       5934.5

如何在调用函数

(1)在sqlplus控制台调用:select 函数名(实际参数) from dual

(2)在java中调用:

package com.lsz.test;

import java.sql.*;

public class TestFunction {

       //如何在java中调用自己编写的函数

       public static void main(String[] args) {

              String sql="select fun1('KING') from dual";

              ResultSet rs=SQLHelper.executeQuery(sql, null);

              try {

                     if(rs.next()){

                            System.out.println(rs.getDouble(1));

                     }

              } catch (Exception e) {

                     e.printStackTrace();

              }finally{

              }

       }

}

函数和包的区别

1.函数必须有返回值,而过程可以没有

2.函数和过程在java中调用方式不一样

函数:select 自己的函数名(列) from 表

过程:使用CallableStatement去完成调用

原文地址:https://www.cnblogs.com/fanweisheng/p/11114100.html