[oracle儲存過程]給表中分好的各組進行組內編號
阿新 • • 發佈:2019-01-27
現在需要給表myrecord的vc_period欄位新增資料(表格建立、資料插入語句在文末附上),新增前後的情況如圖所示:
編寫儲存過程,程式碼如下:
這裡的儲存過程執行一次就完了的那種,還有一種是會寫入oracle資料庫的。(想嘗試儲存過程不同寫法,可以參看[oracle儲存過程]將給定資料與已有的資料做比較)
declare n_lid number; --主鍵id n_projectId number; n_companyId number; group_count number; --當前組擁有的記錄條數 my_counter number; --計數器 --將各個分組的情況存放在遊標中 cursor data_cur is select l_project_id, l_company_id, count(*) from myrecord group by l_project_id, l_company_id order by l_project_id, l_company_id; begin open data_cur; fetch data_cur into n_projectId, n_companyId, group_count; loop exit when not data_cur%found; my_counter:=1; --通過迴圈給各組資料進行編號 for cr in (select l_id, l_project_Id, l_company_id from myrecord where l_project_id = n_projectId and l_company_id = n_companyId order by l_project_id, l_company_id) loop update myrecord set vc_period = my_counter where l_id = cr.l_id; dbms_output.put_line('主鍵id:'||cr.l_id||'====當前計數:'||my_counter); my_counter := my_counter + 1; --如果計數已經超過了該組的記錄條數,說明該組的編號操作已完成 if my_counter > group_count then exit; end if; end loop; --結束迴圈 commit;--如果每組中的資料比較多的話,可以在迴圈完每組後做一次提交;資料少的話,可以在關閉遊標後,一次性全部提交 fetch data_cur into n_projectId, n_companyId, group_count;--繼續從遊標中取資料 end loop; close data_cur; end;
恢復到新增前的狀態:
update myrecord set vc_period = null;
commit;
參考連結:
附註(表格建立、資料插入語句):
-- Create table create table MYRECORD ( l_id NUMBER, l_project_id NUMBER, l_company_id NUMBER, vc_period VARCHAR2(20) ); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (1, 101, 1501, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (2, 101, 1501, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (3, 101, 1501, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (4, 101, 1502, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (5, 101, 1502, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (6, 101, 1502, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (7, 101, 1502, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (8, 102, 1501, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (9, 102, 1501, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (10, 102, 1502, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (11, 102, 1503, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (12, 102, 1503, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (13, 102, 1504, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (14, 103, 1505, null); insert into myrecord (L_ID, L_PROJECT_ID, L_COMPANY_ID, VC_PERIOD) values (15, 103, 1506, null);