Oracle数据库之PLSQL函数

--======函数Function: 必须有返回值===
---function跟过程的最大区别就是 function必须有返回值
-- 过程的返回值可有(输出参数) 可没有 

create or replace function func_name
		[arg_name in|out|in out} argument-type]
	return type is 返回值类型
begin  
	条件语句;
	return value;
exception 
		....
end;

--简单入门
create or replace function f1 
	(p1 in number , p2 out number )  return number 
is begin
	dbms_output.put_line('p1 in' || p1);
	p2 :=2;
	return p2;
end;

--调用
declare
	v_p1 number(4) :=1;
	v_p2 number(4);
begin
	dbms_output.put_line('out '||f1(v_p1,v_p2));
end;
	
--或者绑定变量的调用
variable v_p2 number;
exec dbms_output.put_line(f1(10, :v_p2));
print v_p2;

-- function的操作
--1.创建编译
	create or replace
--2.编译
	alter function f1 compile;
--3.调用
	匿名子程序
	有名子程序
	dml,select语句
--4.删除
	drop function f1;

--根据EMP的id,得到该EMP的sal
create or replace function f1
	(id in number , salary out number ) return number 
is
--	v_sal number(6,2);
begin
	select sal into salary from emp where empno = id;
	return salary;
end;

-- =调用	
variable salary number;	
exec dbms_output.put_line(f1(7900, :salary));


--上述调用比较麻烦,改成如下
create or replace function f1(id in number ) return number 
	is
	v_sal number (6,2);
begin
	select sal into v_sal from emp where empno = id;
	dbms_output.put_line('id '||id);
	return v_sal;
	
	Exception 
		when NO_DATA_FOUND
			then 
			dbms_output.put_line('no emp exists');
end;

--用select执行
select f1(7900) from emp where empno  = 7900;
	
	
	

猜你喜欢

转载自whatisjavabean.iteye.com/blog/2005695