简体   繁体   English

从表中选择特定列的数据,其中查询返回列名称

[英]select data of specific column from table where column names are returned by query

I have written 2 separate queries 我写了2个单独的查询

1) 1)


SELECT COLUMN_NAME
  FROM ALL_TAB_COLUMNS
 WHERE TABLE_NAME =
       (SELECT DISTINCT UT.TABLE_NAME
          FROM USER_TABLES UT
         WHERE UT.TABLE_NAME = 'MY_TABLE')
   AND COLUMN_NAME NOT IN ('AVOID_COLUMN')

2) 2)


    SELECT *
      FROM MY_TABLE MT
     WHERE MT.COL1 = '1'
   

The 1st query returns the names of all the columns except the one I want to avoid. 第一个查询返回除我想要避免的列之外的所有列的名称。 The 2nd one returns data of all the columns from the table. 第二个返回表中所有列的数据。 Is there some way to merge these queries so that only those column's data is selected from the 2nd query, which are returned from the 1st query? 有没有办法合并这些查询,以便从第一个查询返回的第二个查询中只选择那些列的数据?

Thanks in advance 提前致谢

You'll have to use dynamic SQL for this (BTW, I got rid of the subselect for the USER_TABLES query - it's unnecessary): 你必须为此使用动态SQL(顺便说一句,我摆脱了USER_TABLES查询的子选择 - 这是不必要的):

var  cur refcursor
/
declare
  v_stmt varchar2(4000);
begin
  v_stmt := 'SELECT ';  
  for cur in (
    SELECT COLUMN_NAME
    FROM ALL_TAB_COLUMNS
    WHERE TABLE_NAME =
       'MY_TABLE'
    AND COLUMN_NAME NOT IN ('AVOID_COLUMN')
  ) 
  loop
    v_stmt := v_stmt || cur.column_name || ',';
  end loop;
  -- get rid of trailing ','
  v_stmt := regexp_replace(v_stmt, ',$', '');

  v_stmt := v_stmt || ' from my_table MT WHERE MT.COL1 = ''1''';
  dbms_output.put_line(v_stmt);
  open :cur for v_stmt;
end; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM