在数据库中有50多个表,现在要查询出除了khda,khzh,khzmx之外的所有记录总数不是0的表名
该怎么样写SQL呢?

解决方案 »

  1.   


    计算一个库里各个表的记录总数:
    select b.name,a.rowcnt from sysindexes a,sysobjects b 
    where a.id=b.id and a.indid<2 and b.xtype='u'--统计数据库里每个表的详细情况
       EXEC sp_MSforeachtable @command1="sp_spaceused '?'"   --获得每个表的记录数和容量:
       EXEC sp_MSforeachtable @command1="print '?'",
            @command2="sp_spaceused '?'",
            @command3= "SELECT count(*) FROM ? "
      

  2.   

    --获取库中所有表及该表的记录数declare @sql varchar(8000)
    set @sql='select * from ('
    select @sql=@sql+' select name = ''' + name + ''' , count(*) as num from ['+name+'] union all ' from sysobjects where xtype='u'
    set @sql = left(@sql,len(@sql) - 10) + ')a'
    exec(@sql)/*
    --sql server 2000 自带库 pubs 的结果
    name        num         
    ----------- ----------- 
    titleauthor 25
    stores      6
    sales       21
    roysched    86
    discounts   3
    jobs        14
    pub_info    8
    employee    43
    authors     23
    publishers  8
    titles      18
    */
    --查询出除了khda,khzh,khzmx之外的所有记录总数不是0的表名
    declare @sql varchar(8000)
    set @sql='select * from ('
    select @sql=@sql+' select name = ''' + name + ''' , count(*) as num from ['+name+'] union all ' from sysobjects where xtype='u'
    set @sql = left(@sql,len(@sql) - 10) + ')a where name not in (''khda'',''khzh'',''khzmx'') and num > 0 '
    exec(@sql)
      

  3.   


    select b.name,a.rowcnt from sysindexes a,sysobjects b 
    where a.id=b.id and a.indid<2 and b.xtype='u'
    declare @sql varchar(8000)
    set @sql='select * from ('
    select @sql=@sql+' select name = ''' + name + ''' , count(*) as num from ['+name+'] union all ' from sysobjects where xtype='u'
    set @sql = left(@sql,len(@sql) - 10) + ')a'
    exec(@sql)学习