一个字段值作为另一张表名,怎么查询?

yaku2688 2010-09-30 10:47:44
有一张表A,里面有id,name其中name值记录这一些表的表名,如表c,表d,表e的表名

请问如何根据表A中id查询出表c的内容。

此种语句
select * from (select name from A where id='...');
就不用说了,不正确。
...全文
1549 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
心中的彩虹 2010-09-30
  • 打赏
  • 举报
回复
[Quote=引用楼主 yaku2688 的回复:]
有一张表A,里面有id,name其中name值记录这一些表的表名,如表c,表d,表e的表名

请问如何根据表A中id查询出表c的内容。

此种语句
select * from (select name from A where id='...');
就不用说了,不正确。
[/Quote]


--用动态拼接

SQL> edi
已写入 file afiedt.buf

1 declare
2 type cur1_type is ref cursor;
3 cur1 cur1_type;
4 v_tb varchar2(40);
5 v_id varchar2(20);
6 begin
7 select tbname into v_tb from t_tab where rownum=1;
8 open cur1 for 'select id from '||v_tb;
9 fetch cur1 into v_id;
10 while cur1%found loop
11 dbms_output.put_line(v_id);
12 fetch cur1 into v_id;
13 end loop;
14 close cur1;
15* end;
SQL> /

PL/SQL 过程已成功完成。

SQL> set serveroutput on
SQL> /
wkc168
2
2
2
2
2
8
test
11
22
44

PL/SQL 过程已成功完成。





minitoy 2010-09-30
  • 打赏
  • 举报
回复
Connected to Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 
Connected as scott

SQL>
SQL> create table tbl_store
2 (id number(10),
3 name varchar2(10));


Table created

SQL> insert into tbl_store values(1,'emp');

1 row inserted

SQL> commit;

Commit complete

SQL> set serveroutput on
SQL>
SQL> declare
2 cv_emp sys_refcursor;
3 v_table varchar2(10);
4 begin
5 select name into v_table from tbl_store where rownum=1;
6 open cv_emp for 'select ename from '||v_table;
7 loop
8 fetch cv_emp into v_table ;
9 exit when cv_emp%notfound;
10 dbms_output.put_line(v_table);
11 end loop;
12 close cv_emp;
13 end;
14 /

SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

PL/SQL procedure successfully completed

SQL>
caofaping 2010-09-30
  • 打赏
  • 举报
回复

create table a (
name varchar2(20)
);
insert into a(name) values ('a_test');
commit;

create or replace procedure create_table as
table_name varchar2(100);
begin
select t.name into table_name from a t;
execute immediate 'select * from ' || table_name; --动态SQL

end create_table;
minitoy 2010-09-30
  • 打赏
  • 举报
回复
先select name into 变量 from tablea;
然后open cursorname for'select * from '||变量;
yaku2688 2010-09-30
  • 打赏
  • 举报
回复
楼上能说细点吗?
gelyon 2010-09-30
  • 打赏
  • 举报
回复
你要采用动态SQL去做。
sinpoal 2010-09-30
  • 打赏
  • 举报
回复
--用动态sql写
declare
table_name varchar(10);
sql_statement varchar2(100)
begin
select name into table_name from where id=&v_id;
sql_statement:='select * from '||table_name;
execute immediate sql_statement;
end;
yaku2688 2010-09-30
  • 打赏
  • 举报
回复
看来只能用存储过程,本来意思是不用的。

17,140

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧