oracle自定义函数示例--实现时间和数字的来回转换

来源:互联网 发布:mac 邮件登录企业邮箱 编辑:程序博客网 时间:2024/06/07 01:57

用户自定义函数是存储在数据库中的代码块,可以把值返回到调用程序。函数的参数有3种类型:

(1)in参数类型:表示输入给函数的参数,该参数只能用于传值,不能被赋值。

(2)out参数类型:表示参数在函数中被赋值,可以传给函数调用程序,该参数只能用于赋值,不能用于传值。

(3)in out参数类型:表示参数既可以传值,也可以被赋值。

 

1.函数的创建

语法格式:

 

Sql代码  

   create [or replace] function functionName      (          parameterName1 mode1 dataType1,          parameterName2 mode2 dataType2,          ...      )      return returnDataType      is/as      begin          function_body          return expression      end functionName; -- 结束函数的声明,也可以直接写end不加函数名。  --其中mode1、mode2表示参数类型,dataType表示参数的数据类型。returnDataType表示返回值类型。  


接下来通过示例讲解一下:

日期转换为数字:date_to_num

create or replace function date_to_num(thistime date) return number is    Result number(13);  begin    select to_number(thistime - to_date('1970-01-01 08:00:00','YYYY-MM-DD HH24:mi:ss'))*24*60*60    into Result    from dual;    return(Result);  end date_to_num;

数字转换为日期:num_to_date

create or replace function num_to_date(nums number) return varchar2 is    Result varchar2 (100);  begin     select to_char(nums / (60 * 60 * 24) +                 to_date('1970-01-01 08:00:00', 'YYYY-MM-DD HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')        into Result       from dual;    return(Result);end num_to_date;

调用方式:

自定义函数的调用方法跟系统内置函数的调用方法相同,可以直接在select语句中调用,也可以在函数中调用,如下:

select num_to_date(90) from dual;


1 0
原创粉丝点击