oracle 之 函數

來源:互聯網
上載者:User

標籤:

 

本次主題 青澀/色

    函數的結束一定要使用return語句返回一個與聲明匹配的值

--文法:

 create[or replace] function<函數名> [(參數列表)]

 return資料類型

 is|as (is或as完全等價 )

 [局部變數聲明]

 begin

 pl/sql函數體

 end[<函數名>]

 

--函數 沒有參數

create or replace function getCount
return number
as  v_num number;

begin
  select count(*) into v_num from v_emp;
  return v_num;
end;

--調用函數1
select getCount() from dual;
--調用函數2 plsql語句塊
declare
num number;
begin
num := getCount();
dbms_output.put_line(num);
end;

--帶有 in 參數的函數, in 預設 ,可以使用select語句和plsql語句塊調用函數

create or replace function getName(v_name varchar2)
return varchar2
as
v_person v_emp%rowtype;
v_str varchar2(100);
begin
select * into v_person from v_emp where ename = v_name;
v_str := ‘當前人是‘||v_person.ename||‘ 工資是‘||v_person.sal;
return v_str;
end;

--調用函數  select語句

select getPersonByName(‘SMITH‘) from dual;

 --調用函數  plsql語句塊

declare
a_name varchar2(50);
begin
a_name := getName(‘SMITH‘);
dbms_output.put_line(a_name);
end;

 --帶有 out 參數的函數   函數攜有out參數的,只能使用plsql語句塊調用函數

create or replace function getSal(p_name varchar2,e_sal out number)
return varchar2
as
v_st varchar2(100);
begin
select sal into e_sal from v_emp where ename=p_name;
v_st := p_name||‘每個月開‘||e_sal||‘元‘;
return v_st;
end;

--調用函數 plsql語句塊

declare
v_str varchar2(20);
v_sal number;
begin
v_str := getSal(‘SMITH‘,v_sal);
dbms_output.put_line(v_str);
dbms_output.put_line(v_sal);
end;

-- 帶有 in out 參數的函數 同樣有out參數的函數,只能由plsql語句塊調用函數

create or replace function swap(num1 in out number,num2 in out number)
return varchar2
as
temp number;
begin
temp := num1;
num1 := num2;
num2 := temp;
return ‘abc‘;
end;

 --調用函數

declare
num1 number := 10;
num2 number := 20;
v_str varchar2(20);
begin
dbms_output.put_line(num1||‘==========‘||num2);
v_str := swap(num1,num2);
dbms_output.put_line(num1||‘==========‘||num2);
end;

oracle 之 函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.