Oracle建立INSERT儲存過程並呼叫

2021-09-04 05:59:32 字數 3495 閱讀 4421

初學資料庫,對儲存過程一頭霧水,上午學習建立簡單的資料表,由於運維需要用到資料庫儲存,之前生產資料庫定時儲存過程一直失效,於是想自己寫乙個儲存過程,測試下定時儲存任務,後續打算用crontab來定時呼叫儲存過程。下午從網上找了一些儲存過程的例子,理解改寫後往自己的資料庫裡面insert資料,一直在瘋狂報錯,簡直到了喪心病狂的地步,瞬間覺得自己好水,哈哈。後來經過不懈努力(浪費時間)後,總算可以用,下面吧儲存過程的建立放在下面,算是記錄一下。

student2表結構資訊見前一篇部落格:表內容如下,表示學生的一些資訊

這裡我是通過sqlplus建立儲存過程的,依然是用的shell指令碼建立儲存過程,也可以直接登入到資料庫,直接建立儲存過程。

#!/bin/bash

#db="class" #資料庫為class

tb="student2" #需要建立的表是student

pro="insertintostu"

echo "start to create procedure for table name is $tb"

sqlplus ucr_param/'ynnzabc1!'@bosscend 建立儲存過程之前先建立表物件。

重複建立儲存過程會覆蓋?

執行建立指令碼

注意點:入參需要在內部用區域性變數承載其值,並且進行相應的型別轉換,比如由char型別轉換為date型別。

檢視儲存過程內容語句:

select text from all_source where name = upper('insertintostu');

編譯儲存過程:編譯可以確認儲存過程沒有錯誤

--編譯儲存過程

alter procedure insertintostu compile;

#!/bin/bash

tb="student2" #需要建立的表是student

pro="insertintostu" #儲存過程名字

echo "start to calling insert procedure for table name is $tb"

sqlplus ucr_param/'ynnzabc1!'@bosscend 執行結果

查詢檢查結果:

--當年齡為負數的時候,這裡不再執行,丟擲異常後轉向後面的控制語句

insert into student2(sid,sname,sage,s***,saddress,sbirth) values(vs_id,vs_name, vs_age, vs_***,vs_address, vs_birth);

dbms_output.put_line('end join, please check...');

exception

when v_exp then

dbms_output.put_line('age is can not be negative!');

when v_expid then

dbms_output.put_line('id is can not be null!');

commit;

end insertintostu;

/

測試年齡為負數插入

結果沒有插入

注意,丟擲異常語句(raise exception)後,會停止執行後續語句,轉向 exception -- when   then 語句,因此,被保護語句應該在raise exception 之後 ,在exception之前,否則如果放在最後執行插入操作,依然能夠正常插入

測試插入id為null

ORACLE 批量插入 Insert 詳解

假設有一張表student 學生表 create table student id varchar2 11 primary key,name varchar2 32 not null varchar2 3 not null age smallint,tel varchar 16 其中中代表可選 代表...

Oracle中Insert語句的總結

在oracle中,insert語句的使用 1 insert into 表1 列名1,列名2,values 值1,值2,2 insert into 表1 列名1,列名2,select 列名1,列名2,from 表2 3 insert all 無條件新增 into 表1 values 列名1,列名2,i...

oracle高效率insert寫法

這裡我們這邊驗證乙個oracle非常規的高效率insert寫法 建立2個測試表hyper hyperw create table hyper a int create table hyperw a int 插入100萬條記錄 注意 此處耗時嚴重 declare i int 1 begin while...