首页 > 解决方案 > oracle中如何对多个表进行动态选择查询?使用表名和列名作为其他表的值?

问题描述

我有一个表,其中包含模式名称、表名、列名等列。

模式名称 表名 列名
德博 产品 颜色
德博 销售量 数量
德博 顾客 命令

我想执行一个操作,以便根据列作为列名和表作为表名来获取记录计数

select count(colour) as count from dbo.product
select count(quantity) as count from dbo.sales
select count(order) as count from dbo.customer

你能建议我使用 Oracle 数据库实现这一目标的正确步骤吗?提前致谢

预期产出

数数
5
50
150

标签: sqloracledynamic-sql

解决方案


如果您需要获取每个表的每列计数,您可以使用DBMS_XMLGENpackage 使用普通 SQL 来执行此操作,它本质上是动态执行新游标。我认为您可以调整下面的示例查询以满足您的需求(汇总计数或将它们转换为另一种格式)。

with a as (
  select
    'all_tables' as table_name, 'table_name' as column_name
  from dual
  union all
  select 'all_tables', 'tablespace_name' from dual union all
  select 'all_tab_cols', 'column_name' from dual union all
  select 'all_indexes', 'index_name' from dual union all
  select 'all_indexes', 'tablespace_name' from dual
)
select
  table_name,
  column_name,
  cast(extractvalue(
    dbms_xmlgen.getxmltype(
      'select count(' || column_name || ') as cnt' || chr(10) ||
      'from ' || table_name
    ),
    '/ROWSET/ROW/CNT'
  ) as int) as cnt
from a
表名 | COLUMN_NAME | 碳纳米管
:----------- | :---------------- | ----:
所有表 | 表名 | 71
所有表 | 表空间名称 | 43
all_tab_cols | 列名 | 20983
所有索引 | 索引名称 | 81
所有索引 | 表空间名称 | 73

db<>在这里摆弄


推荐阅读