简体   繁体   English

如何计算表中包含PK(PL-SQL)的列数

[英]How to count the number of columns in a table which are PK (PL-SQL)

INTRODUCTION 介绍

I came across this exercise which ask me to write a script which counts how many rows there are, count how many columns, with PKs, there are and the storage consumed. 我遇到了这个练习,要求我编写一个脚本,该脚本计算有多少行,有多少列以及PK,有多少和消耗的存储空间。

Reading the docs I came across this useful line: 阅读文档时,我发现了以下有用的内容:

ANALYZE TABLE table_name COMPUTE STATISTICS FOR TABLE;

This line gathers statistics of a given table_name which then can be accessed as such: 此行收集给定table_name统计信息,然后可以这样访问它:

SELECT *
FROM user_tables
WHERE table_name LIKE 'table_name'

Here it displays a lot from the table we previously inputted but I can't find the number of columns which have PKs and the storage consumed by such table. 在这里,它从我们先前输入的表中显示了很多内容,但是我找不到具有PK的列数以及该表消耗的存储空间。

My TRY AT PL-SQL is: 我对PL-SQL的尝试是:

DECLARE

    v_nom_table VARCHAR2(10);
    v_num_rows NUMBER(100);
    v_num_col_pk NUMBER(100);
    v_num_storage NUMBER(100);

BEGIN

    v_nom_table := &input_nom_table;

    ANALYZE TABLE v_nom_table COMPUTE STATISTICS FOR TABLE;

    SELECT num_row INTO v_num_rows 
    FROM user_tables
    WHERE UPPER(table_name) LIKE UPPER(v_nom_table )

    DBMS_OUTPUT.PUT_LINE(
        'La tabla ' || v_nom_table || ' tiene: ' || v_num_rows || ' filas, ' 
         || v_num_col_pk || ' columnas con PK y ocupa ' || v_num_storage
    );

QUESTION

How do I get the number of columns involved in PK and the storage consumed by the given table? 如何获取PK中涉及的列数以及给定表消耗的存储空间?

A typical solution to list the columns involved in the primary key of a table is to: 列出表主键中涉及的列的典型解决方案是:

  • query Oracle views USER_CONSTRAINTS (or ALL_CONSTRAINTS ) to find the record that relates to the primary key ( CONSTRAINT_TYPE = P ) of thet table 查询Oracle视图USER_CONSTRAINTS (或ALL_CONSTRAINTS )以查找与该表的主键( CONSTRAINT_TYPE = P )相关的记录
  • then lookup the related columns in view USER_CONS_COLUMNS 然后在视图USER_CONS_COLUMNS查找相关列

Consider: 考虑:

SELECT COUNT(*)
FROM user_constraints cons
INNER JOIN user_cons_columns cols ON cons.constraint_name = cols.constraint_name
WHERE cons.constraint_type = 'P' AND cons.table_name = ?

When it comes to computing the storage space consumed by a given table, that's a different question. 在计算给定表占用的存储空间时,这是一个不同的问题。 A solution is to use column BLOCKS from view USER_TABLES . 一种解决方案是使用USER_TABLES视图中的BLOCKS列。 THen all you have to do is multiply this value by the block size of the tablespace in which the table is stored in the ALL_TABLESPACES view, in column BLOCK_SIZE . 您所要做的就是将此值乘以ALL_TABLESPACES视图中BLOCK_SIZE列中存储表的表空间的块大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM