2017-03-08 14 views
0

私は、異なるテーブルに同じデータグループを挿入できるように、行タイプを一般的に更新する方法を探しています。一般的な行を動的に更新しますか?

私の要件は、以下のような非常に似た列を持つ表を取ることです。

create table storedNumber(myNumber number, userName varchar2(4000), userId number, birthDate date); 
/
create table storedVarchar(myVarchar varchar2(4000), userName varchar2(4000), userId number, birthDate date); 

そこから私はそこに3つの同一の列(ユーザー名は、ユーザーID、たbirthDate)で行型を更新する汎用的なソリューションを作成します。ソリューションとユースケースを想像すると、次のようになります。

procedure UpdateRowWithUserInfo(in_tableName varchar2, in_rowType in out generic_row(?), in_userInfo userInfo) is 
begin 
    in_rowType('userName') := in_userInfo.userName; 
    in_rowType('userId') := in_userInfo.userId; 
    in_rowType('birthDate') := in_userInfo.birthDate; 
end; 
/
declare 
    l_userInfo userInfo; 
    l_numberRow storedNumber%rowtype; 
    l_varcharRow storedVarchar%rowtype; 
begin 
    -- This returns a userInfo object from the id with the userName, userId, and birthDate populated 
    l_userInfo := get_userInfo(123); 

    -- Getting some data for the rows 
    l_numberRow.myNumber := 42; 
    l_varcharRow.myVarchar := 'Hello World'; 

    -- This function should update the input row's columns with the input user info 
    UpdateRowWithUserInfo('storedNumber', l_numberRow, l_userInfo); 
    UpdateRowWithUserInfo('storedVarchar', l_varcharRow, l_userInfo); 
end; 

Oracleではこれが可能でしょうか?

答えて

0

これは、Oracleのオブジェクト・リレーショナル機能を使用して行うことができます。

create or replace type userInfo is object 
(
    userName varchar2(100), 
    userId number, 
    birthDate date 
) not final; 

create or replace type userInfoWithNumber under userInfo 
(
    myNumber number 
) not final; 

create or replace type userInfoWithVarchar under userInfo 
(
    myVarchar2 varchar2(100) 
) not final; 

create or replace procedure UpdateRowWithUserInfo(targetUserInfo in out userInfo, sourceUserInfo in userinfo) is 
begin 
    targetUserInfo.userName := sourceUserInfo.userName; 
    targetUserInfo.userId := sourceUserInfo.userId; 
    targetUserInfo.birthDate := sourceUserInfo.birthDate; 
end; 
/

declare 
    l_userInfo userInfo; 
    l_numberRow userInfoWithNumber; 
    l_varcharRow userInfoWithVarchar; 
begin 
    l_userInfo := userInfo('A', 1, date '2000-01-01'); 
    l_numberRow := userInfoWithNumber('B', 2, date '2000-01-02', 42); 
    l_varcharRow := userInfoWithVarchar('C', 3, date '2000-01-03', 'Hello World'); 

    UpdateRowWithUserInfo(l_numberRow, l_userInfo); 
    UpdateRowWithUserInfo(l_varcharRow, l_userInfo); 

    --Print new values to demonstrate that they have changed. 
    --Values were originally "B" and "C" but will now be "A". 
    dbms_output.put_line(l_numberRow.username); 
    dbms_output.put_line(l_varcharRow.username); 
end; 
/

オブジェクトはスキーマに作成する必要がありますので、これはしかし、完全に動的ではありません。 AnyTypesを使用すると、さらに一般的な解決策を作成できます。

しかし、これらのオプションのいずれかを使用しないことをお勧めします。 Oracleは、表、行および列が「ダム」(リレーショナル)である場合に最適です。 スキーマまたはプログラムをスマートにします。汎用オブジェクトを作成する代わりに、単純なテーブルを変更できる動的コードを作成します。

関連する問題