oracle数据库中的函数

在Oracle数据库中,自定义函数实际是一组PL/SQL的语句的组合,并且自定义的函数必须有返回值。

无参函数

create or replace function '函数名' return '返回值的类型' as
	begin
	'函数定义的逻辑'
	end '函数名';

该语句是创建不带任何参数的简单函数。

create or replace function getEmployeeCount return number as
	begin
	declare employee_count number;
		begin
			select count(1) into employee_count from employee;
			return employee_count;
		end ;
	end getEmployeeCount;

该语句创建例一个统计数据表"employee"中一共有多少行数据的函数"getEmployeeCount"。

有参函数

在Oracle数据库中如果需要定义有参的函数时,只需要在声明语句的函数之后添加小括号,并且在小括号中指定参数的数据类型和名称即可。

create or replace function getTableCount(table_name varchar2) return number as
	begin
	declare record_count number;
	query_sql varchar2(200);
		begin
			query_sql := 'select count(1)  from  ' || table_name;
			execute immediate query_sql into record_count;
			return record_count;
		end ;
	end getTableCount;

该语句创建例一个有参函数,该函数可以统计r数据表中任何数据表中一共有多少行数据。其中"execute immediate"表示立刻执行后面的SQL语句(“query_sql”);"||"在Oracle数据库中起拼接的作用,此时"from"后面必须有空格,否则,在拼接时,直接将"from"和"table_name"拼接在一起,这样在定义函数时,不会报错,但是在执行时会报错。

自定义函数的调用

直接使用

select getTableCount('student') from dual;

pl/sql环境中使用

declare table_name varchar2(50);
begin 
	table_bame := 'student';
	dbms_output.put_line('数据表'|| table_name || '的记录数为' || getTableCount(table_name));
end;

函数的确定性

在Oracle数据库中,当一个函数的函数传递参数值一定,函数结果为唯一值时,这样的函数被称为具有确定性的函数。
确定性函数可以根据参数值来缓存执行结果,当一个具有确定性的函数在第二次执行同一个参数值时,Oracle数据库会直接获取缓存值,而不在去执行实际的代码,从而提高工作效率。
Oracle数据库中使用"deterministic"关键字来表示函数具有确定性,但是必须保证该函数在传入相同的参数值时,结果必须为唯一值,否则不能使用"deterministic"关键字来上面该函数。上面的"getTableCount()"函数就不具有确定性,因为数据表中的数据数是可以变的。

create or replace function getWaterAmount(tom number,unitPrice number) 
	return number deterministic as
	begin 
		declare waterAmount number;
		begin 
			if(ton <= 2) then
				waterAmount := unitPrice * ton;
			end if;
			if(ton > 2 and ton <= 4) then
				waterAmount := unitPrice * 2 + (ton - 2) * 2 * unitPrice;
			end if;
			if(ton >  4) then
				waterAmount := unitPrice * 2 + 2 * 2 * unitPrice + unitPrice * 4 * (ton - 4) ;
			end if;
			return waterAmount;
		end;
	end getWaterAmount;

该函数就是一个具有确定性的函数。

删除自定义函数

drop function '函数名';

该语句可以删除自定义的函数。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值