我在架构中的各个表中都有engine_id列。所以我想根据此列所在的整个架构中的engine_id列来计算行数。
Select count(*)
from table_name
where table_name.engine_id = 8;
答案 0 :(得分:2)
没有用户定义的PL / SQL,只使用内置的Oracle功能......
Oracle 11g(甚至可能更低)查询:
select TC.table_name, X.*
from user_tab_columns TC
cross join xmltable(
'/ROWSET/ROW/CNT'
passing
dbms_xmlgen.getXMLType('
select count(1) as cnt
from '||TC.table_name||'
where &columnName = &columnValueAsLiteral
')
columns
cnt integer
) X
where TC.column_name = '&columnName'
;
Oracle 12c +查询:
select TC.table_name, X.*
from user_tab_columns TC
cross apply xmltable(
'/ROWSET/ROW/CNT'
passing
dbms_xmlgen.getXMLType('
select count(1) as cnt
from '||TC.table_name||'
where &columnName = &columnValueAsLiteral
')
columns
cnt integer
) X
where TC.column_name = '&columnName'
;
在你的情况下供应
&columnName
为ENGINE_ID
,&columnValueAsLiteral
为8
。注意:也可以使用12c的with-PLSQL clause,但我无法使其正常工作,因此我不会在此处发布该解决方案。
答案 1 :(得分:0)
您需要PL代码来查询数据字典视图USER_TABLES
,找出哪些表包含您要查找的列,然后根据您的过滤器要求构建动态SQL查询。
你的功能是这样的:
create or replace function find_count (p_column_name varchar2,
p_column_value number)
return number is
v_sql clob; HERE
v_count number;
begin
for i in (select table_name
from user_tab_cols
where column_name = upper(v_column_name)) loop
v_sql :=
v_sql
|| 'select count(*) as cnt from '
|| i.table_name
|| ' where '
|| p_column_name
|| ' = '
|| p_column_value;
v_sql := v_sql || chr (10) || 'union all ';
end loop;
v_sql := substr (v_sql, 1, length (v_sql) - 11);
v_sql := 'select sum(cnt) from (' || v_sql || ')';
execute immediate v_sql into v_count;
return v_count;
end find_count;
/
您可以使用如下查询触发此功能:
select find_count('ENTITY_ID', 1012) as engine_count from dual;
答案 2 :(得分:0)
以下是您应该遵循的步骤
获取包含该列的所有表格。
select table_name from all_tab_columns
where column_name = 'ENGINE_ID';
将上面作为游标创建并在其上运行循环
for records in above_cursor
loop
execute immediate 'select count(*) from ' || records.table_name || 'where engine_id = 8' into some_temp_number_var;
some_total_number_var := some_temp_number_var + some_total_number_var;
end loop;