Oracle Cast使用%TYPE属性

Rob*_*ebe 6 oracle oracle11g

我想在我的SQL语句中使用%TYPE属性转换值.%TYPE属性允许您在自己的声明中使用字段,记录,嵌套表,数据库列或变量的数据类型,而不是对类型名称进行硬编码.

这有效:

insert into t1  select cast(v as varchar2(1)) from t2;
Run Code Online (Sandbox Code Playgroud)

但我想

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:
Run Code Online (Sandbox Code Playgroud)

这个(或类似的东西)可以完成吗?

编辑:我想要实现的是:当t2.v很大时我想截断它.我试图避免使用具有硬编码字段长度的substr.所以强制转换(v为t1.v%TYPE)而不是substr(v,1,1)

Ale*_*ole 5

%TYPE仅在PL/SQL中可用,并且只能在声明部分中使用.所以,你不能做你正在尝试的事情.

您可能认为可以声明自己的PL/SQL(子)类型并在语句中使用它:

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

...但这也行不通,因为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;
Run Code Online (Sandbox Code Playgroud)

如果您可以将该长度存储在变量中 - 在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;
Run Code Online (Sandbox Code Playgroud)

类似的东西可以在其他设置中完成,它取决于执行插入的位置.