sql - 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 |
解决方案
如果您需要获取每个表的每列计数,您可以使用DBMS_XMLGEN
package 使用普通 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<>在这里摆弄
推荐阅读
- css - 用css放两个圆形梯形,
- python - Python 编码重复相同的字符串 10 次,每个字符串都有计数
- python - 在Robot Framework Selenium中没有唯一ID的情况下如何单击元素
- r - 如何在文档标题前插入徽标?
- reactjs - React/Redux - 将 this.props.history 传递给 thunk 是一种反模式吗?
- laravel-5 - 为什么图片值没有从 laravel 表单上传到数据库?
- python-3.x - pandas:csv文件,为什么连接后有缺失值?
- python - 如何在 Python 中将多个值从一个函数返回到另一个函数?
- java - android.view.InflateException 和 NavigationView 错误导致的错误
- ios - 为什么 IBOutlet var 在模拟器上运行时具有价值,但在设备上运行时产生 nil?