2012-10-18 59 views
6

我想在我的SQL語句中使用%TYPE屬性強制轉換一個值。 %TYPE屬性允許您在自己的聲明中使用字段,記錄,嵌套表,數據庫列或變量的數據類型,而不是對類型名稱進行硬編碼。Oracle Cast使用%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。所以強制轉換(v爲t1.v%TYPE)而不是substr(v,1,1)

回答

5

%TYPE僅在PL/SQL中可用,並且只能在declaration section of a block中使用。所以,你不能做你想做的事。

你可能會認爲你可以聲明自己的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,只能識別內置和模式級別的集合類型;並且您也不能使用%TYPE創建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中的替代或綁定變量*另外,還是PL/SQL中的局部變量。例如,如果它是通過SQL *直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; 

類似的事情在其他的調校可以做,這取決於所執行的插入其中。

+1

'+ 1',恭喜達到'10k' :) –

+0

@PeterLang - thanks * 8-)猜猜我最好去看看版主工具然後... –

+0

@Alex這正是我所知道的試圖實現。當t2.v很大時,我想截斷它。我試圖避免使用具有硬編碼字段長度的substr。所以投(v作爲t1.v%TYPE)而不是substr(v,1,1) –