PLSQL-如何计算动态查询返回的列数

时间:2018-11-28 16:29:29

标签: sql oracle plsql dynamic-sql

我将查询返回为VARCHAR,例如。

varchar_query := 'select unit_id, cart_id from unit';

但是我不知道将返回多少列,因为查询将是动态的。我也不会知道列的数据类型。 在这种情况下,我希望结果返回2。我使用的是PL / SQL,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

简单的例子:

declare 
  varchar_query varchar(1000) := 'select * from user_tables';
  my_cursor sys_refcursor;
  columns_count number;
  describe_Table dbms_sql.desc_tab;
  cursor_number integer;
begin
  open my_cursor for varchar_query;
  cursor_number := dbms_sql.to_cursor_number(my_cursor);
  dbms_sql.describe_columns(
         c       => cursor_number,
         col_cnt => columns_count,
         desc_t  => describe_Table 
  );
  dbms_output.put_line( 'The result of query has ' || columns_count || ' columns' );
  dbms_output.put_line( '=== list of columns =====' );
  for i in 1 .. columns_count loop
     dbms_output.put_line( describe_Table(i).col_name );
  end loop;
  DBMS_SQL.CLOSE_CURSOR( cursor_number );
end;
/

和结果:

The result of query has 64 columns
=== list of columns =====
TABLE_NAME
TABLESPACE_NAME
CLUSTER_NAME
IOT_NAME
STATUS
PCT_FREE
PCT_USED
INI_TRANS
MAX_TRANS
INITIAL_EXTENT
NEXT_EXTENT
MIN_EXTENTS
MAX_EXTENTS
PCT_INCREASE
FREELISTS
FREELIST_GROUPS
LOGGING
BACKED_UP
NUM_ROWS
BLOCKS
EMPTY_BLOCKS
AVG_SPACE
CHAIN_CNT
AVG_ROW_LEN
AVG_SPACE_FREELIST_BLOCKS
NUM_FREELIST_BLOCKS
DEGREE
INSTANCES
CACHE
TABLE_LOCK
SAMPLE_SIZE
LAST_ANALYZED
PARTITIONED
IOT_TYPE
TEMPORARY
SECONDARY
NESTED
BUFFER_POOL
FLASH_CACHE
CELL_FLASH_CACHE
ROW_MOVEMENT
GLOBAL_STATS
USER_STATS
DURATION
SKIP_CORRUPT
MONITORING
CLUSTER_OWNER
DEPENDENCIES
COMPRESSION
COMPRESS_FOR
DROPPED
READ_ONLY
SEGMENT_CREATED
RESULT_CACHE
CLUSTERING
ACTIVITY_TRACKING
DML_TIMESTAMP
HAS_IDENTITY
CONTAINER_DATA
INMEMORY
INMEMORY_PRIORITY
INMEMORY_DISTRIBUTE
INMEMORY_COMPRESSION
INMEMORY_DUPLICATE