Oracle数据库中所有表中的数字列的最大范围和最高值

时间:2015-12-31 15:10:04

标签: oracle

我使用以下查询获取Oracle数据库中所有表的所有列的最大范围

    select OWNER,TABLE_NAME,COLUMN_NAME,DATA_PRECISION,(POWER(10,DATA_PRECISION) -1) 
from ALL_TAB_COLUMNS where OWNER = 'MASTER' and DATA_TYPE = 'NUMBER' and 
DATA_PRECISION is NOT NULL order by TABLE_NAME ASC;


OWNER    TABLE_NAME  COLUMN_NAME   DATA_PRECISION  (POWER(10,DATA_PRECISION) -1)
MASTER    TABLE_1      COL_1            7            9999999
MASTER    TABLE_1      COL_5            7            9999999
MASTER    TABLE_2      COL_3            10           9999999999

我正试图获得第6名&第7列,该列应该是该特定表中该列的最大值,以及最大范围(即(POWER(10,DATA_PRECISION)-1))与表中实际最大值之间的差异。

例如:

OWNER    TABLE_NAME  COLUMN_NAME   DATA_PRECISION  (POWER(10,DATA_PRECISION) -1)   MAX_VALUE     DIFF
MASTER    TABLE_1      COL_1            7            9999999                         9994637     5362
MASTER    TABLE_1      COL_5            7            9999999                         9997637     2362
MASTER    TABLE_2      COL_3            10           9999999999                    8933999999    1066000000

如何实现这一目标?

我可以使用TABLE_NAME加入表格吗?

打赌,这对很多人都有帮助。

2 个答案:

答案 0 :(得分:2)

最简单的方法是编写一个小函数,您可以像这样提供表名和列:

  CREATE OR REPLACE FUNCTION get_max_value (p_table_name VARCHAR2, p_column VARCHAR2) 
    RETURN NUMBER IS
    v_query VARCHAR2(1000);
    v_max_value NUMBER;
BEGIN
    v_query := 'SELECT MAX (' || p_column ||') FROM '
        ||  p_table_name ;
    EXECUTE IMMEDIATE v_query
        INTO v_max_value;
    RETURN v_max_value;
END;

然后是上面查询的略微修改版本:

 SELECT   owner,
         table_name,
         column_name,
         data_precision,
         (POWER(10,data_precision) -1) ,
         get_max_value (owner || '.' || table_name, column_name) max_val 
FROM    all_tab_columns   
WHERE   1 = 1 
AND     owner = 'MASTER' 
AND     data_type = 'NUMBER'   
AND     data_precision is NOT NULL 
AND     table_name NOT LIKE  '%$%'
ORDER BY c.table_name ASC

请注意,根据表的数量和每个表中的行数,执行可能需要一段时间。

答案 1 :(得分:0)

将DBA_TAB_COLUMNS.HIGH_VALUE转换为Beginning ARC in iOS 5 Tutorial

中所述的最大值

收集表统计信息时会记录最大值和最小值。如果使用默认估计百分比,并且最近收集了统计数据,则该值将是准确的。

create or replace function raw_to_num(i_raw raw) 
return number 
as 
    m_n number; 
begin 
    dbms_stats.convert_raw_value(i_raw,m_n); 
    return m_n; 
end; 
/  

select owner,table_name,column_name,data_precision
    ,(power(10,data_precision) -1) max_range
    ,raw_to_num(high_value) max_value
    ,(power(10,data_precision) -1) - raw_to_num(high_value) diff
from dba_tab_columns
where data_type = 'NUMBER'
    and owner = user
    --Add conditions for specific users and tables.
order by owner, table_name, column_name;