当前位置: 数据库>sqlserver
sql 查询所有表的记录数的三种实现方法
来源: 互联网 发布时间:2014-08-29
本文导语: 完整代码如下。 --方法1,利用系统函数sp_MSforeachtable,任何表名都支持 CREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT) EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(*) FROM ?' SELECT TableName, RowCnt FROM #temp ORDER BY TableName DROP TABLE #te...
完整代码如下。
--方法1,利用系统函数sp_MSforeachtable,任何表名都支持 CREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT) EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(*) FROM ?' SELECT TableName, RowCnt FROM #temp ORDER BY TableName DROP TABLE #temp --方法2,自己写函数,有问题,因为数据库用户表名USER,可能和系统表冲突,修改后可以正常运行,结果正确 declare @sql varchar(8000),@count int,@step int set nocount on --@step越大运行速度越快,但如果太大会造成生成的sql字符串超出限制导致语句不完整出错,建议为50 set @step = 50 if object_id(N'tempdb.db.#temp') is not null drop table #temp create table #temp (name sysname,count numeric(18)) if object_id(N'tempdb.db.#temp1') is not null drop table #temp1 create table #temp1 (id int identity(1,1),name sysname) insert into #temp1(name) select name from sysobjects where xtype = 'u'; set @count = @@rowcount while @count>0 begin set @sql = '' select @sql = @sql + ' select ''' + name + ''',count(1) from ' + name + ' union' from #temp1 where id > @count - @step and id
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
站内导航:
特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!