9

SQL ステートメントで %TYPE 属性を使用して値をキャストしたいと考えています。%TYPE 属性を使用すると、型名をハードコーディングするのではなく、独自の宣言でフィールド、レコード、ネストされたテーブル、データベース列、または変数のデータ型を使用できます。

これは機能します:

insert into t1  select cast(v as varchar2(1)) from t2;

しかし、私はしたいです

insert into t1  select cast(v as t1.v%TYPE) from t2;

Error starting at line 16 in command:
insert into t1  select cast(v as t1.v%TYPE) from t2
Error at Command Line:16 Column:37
Error report:
SQL Error: ORA-00911: Ongeldig teken.
00911. 00000 -  "invalid character"
*Cause:    identifiers may not start with any ASCII character other than
           letters and numbers.  $#_ are also allowed after the first
           character.  Identifiers enclosed by doublequotes may contain
           any character other than a doublequote.  Alternative quotes
           (q'#...#') cannot use spaces, tabs, or carriage returns as
           delimiters.  For all other contexts, consult the SQL Language
           Reference Manual.
*Action:

これ(または同様のこと)を行うことはできますか?

編集: 私が達成しようとしているのは: t2.v が大きすぎる場合は切り捨てたいです。ハードコードされたフィールド長で substr を使用しないようにしています。したがって、substr(v,1,1) の代わりにキャスト(v as t1.v%TYPE)

4

1 に答える 1

7

%TYPEPL/SQLでのみ使用可能で、ブロックの宣言セクションでのみ使用できます。だから、あなたがしようとしていることをすることはできません。

独自の PL/SQL (サブ) 型を宣言し、それをステートメントで使用できると思うかもしれません。

declare
    subtype my_type is t1.v%type;
begin
    insert into t1 select cast(v as my_type) from t2;
end;
/

...しかしcast()、SQL関数はPL/SQL関数ではなく、組み込みおよびスキーマレベルのコレクション型のみを認識するため、これも機能しません。いずれかを使用してSQL タイプを作成することはできません%TYPE


厄介なハックとして、次のようなことができます:

insert into t1 select substr(v, 1,
    select data_length
    from user_tab_columns
    where table_name = 'T1'
    and column_name = 'V') from t2;

その長さを変数 (SQL*Plus の置換変数またはバインド変数、または PL/SQL のローカル変数) に格納できるとしたら、これは少しおいしいでしょう。たとえば、SQL*Plus を介した単純な SQL 更新の場合は、バインド変数を使用できます。

var t1_v_len number;
begin
    select data_length into :t1_v_len
    from user_tab_columns
    where table_name = 'T1' and column_name = 'V';
end;
/
insert into t1 select substr(v, 1, :t1_v_len) from t2;

他のセットアップでも同様のことができますが、挿入が実行される場所によって異なります。

于 2012-10-18T10:12:13.683 に答える