블로그 이미지
Sunny's

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

'sp_MSforeachtable'에 해당되는 글 1

  1. 2010.08.19 MSSQL sysobjects 활용
2010. 8. 19. 09:19 MSSQL

SQL Server 관리 시에 sysobjects 를 많이 이용하는데, 다음 두 가지 Procedure를 배우게 되면, 아주 쉽게 관리할 수 있겠더군요.


sp_MSforeachtable : 현재 사용중인 DB의 모든 table을 열거합니다.

예 : EXEC sp_MSforeachtable 'DBCC CLEANTABLE(''Northwind'', ''?'')'

sp_MSforeachdb : 현재 연결된 DB서버의 모든 Database를 열거합니다.

예 : EXEC sp_MSforeachdb 'DBCC CHECKDB (''?'')'



Here is my code for getting the row counts for each table in a database using a CURSOR:


use pubs
go
set nocount on

declare @cnt int

declare @table varchar(128)
declare @cmd varchar(500)
create table #rowcount (tablename varchar(128), rowcnt int)
declare tables cursor for








select table_name from information_schema.tables
where table_type = 'base table'
open tables fetch next from tables into @table
while @@fetch_status = 0
begin
set @cmd = 'select ''' + @table + ''', count(*) from ' + @table
insert into #rowcount exec (@cmd)
fetch next from tables into @table
end CLOSE tables
DEALLOCATE tables


select top 5 * from #rowcount

order by tablename

drop table #rowcount







     

Here is the output of my CURSOR example when the above code in run on my machine:

tablename rowcnt ------------- ----------- authors 23 discounts 3 employee 43 jobs 8 pub_info 8









 

Now here is my code that produces similar results using the undocumented SP_MSforeachtable": 

use pubs
go
create table #rowcount (tablename varchar(128), rowcnt int)
exec sp_MSforeachtable
   'insert into #rowcount select ''?'', count(*) from ?'
select top 5 * from #rowcount
    order by tablename
drop table #rowcount


Here is the output from the above code when run on my machine:

tablename         rowcnt     
----------------- -----------
[dbo].[authors]   23
[dbo].[discounts  3
[dbo].[employee]  43
[dbo].[jobs]      14
[dbo].[pub_info]  8
 
posted by Sunny's
prev 1 next