Oracle

ID更新後,從另一個表中獲取一個值

  • February 23, 2022

我有一張roads桌子:

+---------+---------+
| ROAD_ID | MEASURE |
+---------+---------+
|       1 |    1000 |
|       2 |     100 |
|       3 |     500 |
|       4 |    9000 |
+---------+---------+

我有一個相關的線性參考表,稱為projects

+------------+---------+--------------+------------+
| PROJECT_ID | ROAD_ID | FROM_MEASURE | TO_MEASURE |
+------------+---------+--------------+------------+
|        101 |       1 |            0 |         50 |
|        102 |       1 |          100 |        500 |
+------------+---------+--------------+------------+
|        103 |       2 |            0 |        100 |
+------------+---------+--------------+------------+
|        104 |       3 |          100 |        200 |
|        105 |       3 |          400 |        500 |
+------------+---------+--------------+------------+

使用者手動將項目輸入到應用程序的屬性編輯環境中(更多在這裡)。

進入新項目的工作流程是:

  1. 使用者創建一個空白的新記錄。
  2. FROM_MEASURE預設值為0
  3. 使用者ROAD_ID手動輸入。
  4. 使用者TO_MEASURE 手動輸入。

您無法從範例表中看出,但十分之九的項目涉及整條道路(不僅僅是道路的一部分)。一個例子是PROJECT #103

與其讓使用者TO_MEASURE在估算新項目時手動輸入,是否可以在ROAD_ID輸入後自動獲取這些值?


例子:

  1. 使用者創建一個空白的新記錄。
  2. FROM_MEASURE預設值為0

+------------+---------+--------------+------------+
| PROJECT_ID | ROAD_ID | FROM_MEASURE | TO_MEASURE |
+------------+---------+--------------+------------+
|        106 |         |            0 |            |
+------------+---------+--------------+------------+
  1. 使用者ROAD_ID手動輸入。
  2. TO_MEASURE自動檢索

+------------+---------+--------------+------------+
| PROJECT_ID | ROAD_ID | FROM_MEASURE | TO_MEASURE |
+------------+---------+--------------+------------+
|        106 |       4 |            0 |      9000  | <-- Magic!
+------------+---------+--------------+------------+

After ROAD_ID is updated, automatically get the related road's MEASURE value as the TO_MEASURE.

使用觸發器很容易在數據庫中執行此操作。但是,在數據庫中這樣做很好,但我們不知道應用程序本身如何工作或將處理這個問題(如果有的話)。例如,應用程序可能會顯示使用者輸入的內容,而不是觸發器自動插入的值。我認為你將不得不在前端處理這個問題,這是我們可能無法幫助你的事情。

無論如何,這裡是如何編寫一個觸發器來做到這一點。

測試表和數據:

create table roads
(
road_id number primary key,
measure number
);

create table projects
(
project_id number,
road_id number,
from_measure number,
to_measure number
);

insert into roads values(1,1000);
insert into roads values(2,100);
insert into roads values(3,500);

扳機:

create or replace trigger projects_btrig
before insert on projects
for each row
declare
   v_measure number;
begin
   select measure 
   into v_measure
   from roads 
   where road_id = :new.road_id;

   :new.to_measure := v_measure;
end;
/

測試:

SQL> insert into projects (project_id, road_id, from_measure) values (1,1,0);

1 row created.

SQL> select * from projects;

PROJECT_ID    ROAD_ID FROM_MEASURE TO_MEASURE
---------- ---------- ------------ ----------
    1         1            0          1000

SQL>

引用自:https://dba.stackexchange.com/questions/176934