2016-01-12 39 views
0

我將從一個表中獲取每一行,並在另一個表中找到等價物。然後,我將通過使用已獲得的id更新第二個表的行。 我試圖運行我的腳本,但我遇到了一些問題。 其實我試圖做一個循環,然後把每行的ID在一個變量將其用於我的更新語句,但PL表明了我,告訴我一個錯誤「找不到數據」匹配和更新兩個表

我未完成的腳本

DECLARE 
tbl1Count number(4); 
counter number(4); 
MyO66ID number(8); 
Begin 
select Count(*) INTO tbl1Count from crbank ; 
<<my_loop>> 
For counter IN 1..tbl1Count-1 Loop 
    select O66ID INTO MyO66ID from crbank where rownum=counter;  
    End loop my_loop; 
End; 
+0

你應該包括兩個表的DDL。 –

+0

@OzgurBar ddls是什麼? –

+0

我的意思是結構(列,列類型,如果需要)給用戶一個想法提到的表。像'tbl1(id,name,....等); TBL2(ID2,NAME2,...,等等)'。 –

回答

-2
Try this one using cursor in sql. 

Declare @id bigint 

DECLARE CUR CURSOR FOR 

select data from table1 

open CUR 

Fetch next from cur into @id 

while @@FETCH_STATUS=0 
begin 
update table2 set columnname=value where [email protected] 
Fetch next from cur into @id 
end 

CLOSE CUR  
DEALLOCATE CUR 
+0

這一個似乎SQL Server? ,光標也不建議使用。 – Japongskie

+0

問題是關於Oracle(PL/SQL),而不是SQL Server(T-SQL) –

0

你在這種情況下

寫了一個奇怪的邏輯這應該工作:

DECLARE 
    tbl1Count number(4) :=0; 
    MyO66ID number(8); 
Begin 
    -- select Count(*) INTO tbl1Count from crbank; -- not needed at all 

    For myItems IN (select O66ID, ROWNUM, whatever_columns_you_need from crbank) Loop 
     MyO66ID := myItems.O66ID; 
     tbl1Count := tbl1Count + 1; -- this will serve you better than the first select if you are concerned of the number of rows you have. 

     /* 
      Do your logic here for the values you have in the myItems object 
      EX: update yourTable set yourColumn = myItems.otherColumn where id= myItems.something 
      You dont need variables to be defined if you noticed as in the above example. 
     */ 


    End loop; 
End; 

提示:

你得到count,那麼你得到的計數循環,並與rownum匹配它,這是不是最佳做法;!打你的數據庫兩次,countselect,雖然可以做到這一點在一次循環,沒必要爲第一選擇

rownum將爲每個select語句不同,這取決於您指定的順序,因此,它是明智地使用它?

0

你已經在你的問題中提到

我要每一行從一個表中提取並找到另一個表

甲骨文相當於只是有一種變通方法對於這種類型的條件。 MERGE語句在這些典型場景中非常有用。考慮下面的插圖片段。讓我知道這是否有幫助。

只要可能嘗試使用純SQL在PL/SQL

MERGE INTO <Update_table> USING <LOOKUP_TABLE> 
ON 
(UPDATE_TABLE.COLUMN_NAME = LOOKUP_TABLE.COLUMN_NAME) 
WHEN MATCHED THEN 
UPDATE SET 
<UPDATE_TABLE.COLUMN_NAME> = <Update_value> 
;