2014-01-05 129 views
1

這裏的高數列如何從oracle中已有記錄的表中找到記錄?

create table test (
id number, 
col_1 varchar2(50), 
col_2 varchar2(50), 
. 
. 
col_n varchar2(50) 
); 

和表的表填充一些示例數據

insert into test values(1,'a1','a2',...,'an'); 
insert into test values(2,'a1','a3',...,'am'); 
insert into test values(3,'a4','a2',...,'ax'); 

現在我需要複製一行(前面例子中,一行ID = 1 )並且只改變一列的值,如果結果與另一行不相似(不考慮id)。 一些事情是這樣的:

declare 
r test%rowtype; 
var1 number; 
begin 
insert into r from test where id = 1; 
r.col_2='a3'; 
select count (*) into var1 from test where 'the row without id' = r; 
if (var1 = 0) then 
    insert into test values r; 
end if; 
end; 

,但我不知道如何寫在Oracle中選擇部分。考慮表測試有很多列,所以你不能在where子句中寫出所有的列。

+1

甲骨文並沒有真正限制可被引用的列數了'where'條款,它限制列數一張桌子。如果只有很多列,使用元數據表來提取它們並生成代碼。 –

+1

[相關問題,也許,但不完全相同](http://stackoverflow.com/q/9133120/266304)。也許還值得考慮一下,當你進行計數和插入時間之間的競爭條件的可能性;一個小窗口,但兩個會話仍然可能會衝突並插入重複項。所有列的唯一索引可能是可以接受的開銷,但可以考慮,也可能會加快計數。 –

+0

也許在'select'查詢中'where id爲null'? – Rachcha

回答

2

這是很難理解你需要什麼。我會在這裏射門。讓我知道如果這是軌道上....

爲了使事情變得容易,你可以在表上創建一個唯一的索引?

create unique index test_uidx on test (col_1, col_2, ... col_n); 

然後讓Oracle做的工作:

declare 
     r  test%rowtype; 
     var1 number; 
    begin 
     select * into r from test where id=1; --- get the row 
     r.col_1 := 'some new value';   --- change 1 value 

     begin 
     insert into test values r;   --- insert the row 
     exception 
     when dup_val_on_index then   --- row was a dup 
      null;        --- and did not insert 
     end; 
    end; 
+0

我想我可以創建一個索引。它是如何工作的?它是否先插入行,如果插入的行重複,oracle會刪除該行?你能解釋更多嗎? –

+0

當一行被重複時,它不會被插入,並且會發生異常 – hmmftg

+1

當引發異常時,控制進入異常處理程序,記錄不會被插入,並且「null」行已到達,然後繼續處理。如果「null」;被改爲「提高」;那麼會引發dup_val_on_index錯誤。只是做「空」;錯誤被抑制。合理? –

相關問題