2013-06-12 37 views
0

基本上我想从表中选择基于另一个表的ID的数据。所以算法如下:PL/SQL循环

foreach i in (select distinct id from table1) 
{ 
    select * from table2 where table2.id=i; 
} 

如何使用SQL查询执行此功能?我明白,我们可以使用连接等代替循环,但是,我的要求是,我需要仅在for循环中传递id。

+0

使用连接到两个表,或子查询数据从一个只得到数据。 –

+0

我的要求是,我必须一次只传递一个id。这是因为表2的数据量非常大,只是使用WHERE子句,给出了临时表空间错误。但是,如果我使用特定的ID查询大量表,它会返回所需的值 – user1703096

+2

然后发布您正在使用的查询,执行计划,表定义和** exact **错误消息。你不需要PL/SQL。一个普通的SQL查询将会执行。 –

回答

1
select * from table2 where table2.id IN (select distinct id from table1) 
+0

我尝试过使用IN,EXISTS。这些也给临时表空间问题。如果我一次只能通过一个id,我将能够得到结果 – user1703096

1

使用for而不是foreach

将PL/SQL为begin .... end;块(见下文的declare

=i应该读=i.idi是SELECT语句的完整记录,但你只能在它id领域感兴趣。

在PL/SQL中,select语句必须被提取into一个变量。因此,您必须声明一个相应的变量:r table1%rowtype

此类变量的声明位于PL/SQL块的declare ...部分。

的“算法”就变成

declare 
    r table2%rowtype; 
begin 
    for i in (select distinct id from table1) loop 
    select * into r from table2 where table2.id = i.id; 
    end loop; 
end; 
+0

感谢您的回复。我尝试使用上述查询,但无法声明table2。我通过DBLink访问它。所以我写了这样的查询: declare table2 [email protected]; r table2%rowtype; 开始 为我in(从table1中选择不同的id)循环 从table2中select * into r,其中table2.id = i.id; end loop; 结束; 这是给出的错误 – user1703096

+0

'declare r table2 @ dblink%rowtype;' –

+0

但是如何在select子句中使用这个table2。如何给这个别名? – user1703096