1. 程式人生 > 其它 >函式失敗返回_10.oracle建立函式--無參案例

函式失敗返回_10.oracle建立函式--無參案例

技術標籤:函式失敗返回

1.什麼是函式:

函式(Function)為一命名的儲存程式,可帶引數,並返回一個計算值。函式和儲存過程的結構類似,但必須有一個RETURN子句,用於返回函式值。函式說明要指定函式名、結果值的型別,以及引數型別等。

2.建立函式結構

e74d268c76aa771d7a6a5369a6caef87.png

3.刪除函式

drop function 函式名

4.呼叫函式

1.sql呼叫

select 函式名 from dual; (dual是個虛擬表)

2.pl/sql呼叫

declare
ff varchar(20);
begin
ff:=函式名;
dbms_output.put_line(ff);
end;

5.案例(無參+有參)

  • 無參案例:(此案例包含函式知識+序列知識+隨機數)
  1. --寫一個pl/sql塊,插入表employ中100條資料。
  2. --插入該表中欄位id用序列seq_employee實現,薪水和姓名欄位可以任意填寫
  3. --建立函式f_employ實現更新員工薪水的功能,將薪水低於5000且ename欄位中有E字元的員工薪水加5%,其他不變,更新成功則返回1,否則返回0;(如果更新超過1條資料,那就算更新成功返回1,如果沒有找到,資料可被更新,那麼算失敗,返回0;)
//先建立一個空表
create table employ(
        id number(10),
        name varchar2(20),
        sal number(10)
);

//再建立一個序列,自動生成id欄位
create sequence idseq  start with 1 maxvalue 1000 minvalue 1 cache 20 increment by 1;

//向表裡插入隨機資料
declare 
vname varchar2(20);
vsal number(10);
begin
   for i in 1..100 loop
      select dbms_random.string('U',5) into vname from dual;
      select round(dbms_random.value(1000,10000)) into vsal from dual;
      insert into employ values(idseq.nextval,vname,vsal);
  end loop;
end;

//準備完成做完,開始做正題
create function  f_employ
return number
as
i number:=0;
cursor c is select * from employ where sal<5000 and name like '%E%';
begin
   for v in c loop
        update employ set sal=sal*1.05;
        i:=i+1;
   end loop;
   if i>0 then
   return 1;
   else
   return 0;
   end if;
end;

//呼叫函式   如果程式中有DML語句,則不能用sql語句呼叫,只能用pl/sql語句來呼叫
declare
f number(10);
begin
   f:=f_employ;
   dbms_output.put_line(f);
end;

上面開始做題那一塊,我是用的顯性遊標,其實用隱性遊標更簡單

create function  f_employ
return number
as
begin
    update employ set sal=sal*1.05 where ename like '%E%' AND SAL<5000 ;
    if SQL%ROWCOUNT >0 then
        return 1;
    else
        return 0;
    end if;
end;
  • 我的展示結果

4d99cdb3aa814548ac14d4c075d34831.png