2013-07-10 65 views
0

我有一个数据库名称AT。在这个数据库150表。我想创建一个语句来返回数据库中所有表的行数和列数。Sybase数据库中所有表中的行数列数

我已经创建了一个存储过程对于SQL SERVER 2008,但我不知道如何为Sybase编写此脚本。

回答

2

Sybase ASA有许多系统表,为您提供有关数据库结构的信息。您感兴趣的两个表格是SYSTABLE(所有表格)和SYSCOLUMN(所有栏目)。

我试过这个快速和肮脏的存储过程,适合我(在年龄相当老的ASA版本8!)。它创建一个临时表和一个光标来遍历所有表。对于每个表,将表名,列数和行数插入临时表并最终返回。

(提示:在tablefilter允许只返回整个数据库的一个子集,如果你有很多表)

CREATE PROCEDURE Usr_TableStats(in par_tablefilter char(100)) 
RESULT (tablename varchar(255), number_of_cols int, number_of_rows int) 
BEGIN 

    declare err_notfound exception for sqlstate value '02000'; 
    declare @table_id integer; 
    declare @tablename varchar(100); 
    declare @cols  integer; 
    declare @sql  varchar(300); 

    declare tables no scroll cursor for select table_id, table_name from sys.systable where table_type = 'BASE' and table_name like par_tablefilter || '%' order by table_name; 

    create table #tablestats (
     tablename  varchar(100) not null, 
     number_of_cols int not null default 0, 
     number_of_rows int not null default 0 
    ); 

    open tables; 

    LoopTables: loop 

     fetch next tables into @table_id, @tablename; 

     if sqlstate = err_notfound then 
      leave LoopTables 
     else 
      SELECT COUNT(column_id) INTO @cols FROM SYSCOLUMN WHERE table_id = @table_id; 
      set @sql= 'INSERT INTO #tablestats SELECT ''' || @tablename || ''', ' || @cols || ', COUNT(*) FROM ' || @tablename || ';'; 
      EXECUTE IMMEDIATE WITH QUOTES @sql; 
     end if 

    end loop LoopTables; 

    close tables; 

    SELECT tablename, number_of_cols, number_of_rows FROM #tablestats; 

END 

调用它在iSQL这样的:

CALL Usr_TableStats('%'); -- all tables 
CALL Usr_TableStats('ADDRESS%'); -- only tables starting with ADDRESS 
0

sys.systable和sys.syscolumn应为您提供以下信息:

Select st.table_name, 
    st.count as row_count, 
    col_count = (SELECT count(*) FROM sys.syscolumn where table_id = st.table_id) 
    from SYS.SYSTABLE st where st.creator <> 0 and st.count > 0 
    order by st.table_name 
相关问题