其实只要使用系统内置的存储过程sp_spaceused就可以得到表的相关信息
3 U% E8 y1 T) I$ O# N $ I4 B' F7 G Z* ]! [ 如:sp_spaceused 'tablename'
7 t0 P- Y! g# Q l( z6 V+ t+ t ( F! n! ?; w# ?+ w 以下是为了方便写的一个存储过程,目的是把当前的所有表的相关信息全部都保存在一个指定的表里面
4 |' |* @8 n& m+ R' S+ H . G9 S- j2 E- }( T CREATE PROCEDURE get_tableinfo AS
0 ~: d% ^: x( @: `& ~2 n) R% }3 y7 y 2 I- l$ @4 T. b1 a0 X0 P7 n, U if not exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[tablespaceinfo]') and OBJECTPROPERTY(id,N'IsUserTable') = 1)
6 r5 P: p0 T) z6 ]1 e2 ~ create table tablespaceinfo --创建结果存储表
1 m- M6 q6 V" v( t8 ~/ p (nameinfo varchar(50) ,
4 @# X2 M4 X0 ?) ~# }# L B, x rowsinfo int , reserved varchar(20) ,
# q6 R; u6 X' M2 p0 F+ o datainfo varchar(20) ,
9 {. `# X" Q- C* }( e index_size varchar(20) ,
% _9 O& v5 r7 u; q4 L7 Y G unused varchar(20) )
) b/ K4 J8 \& X; P; W5 L + }& f3 b6 S8 i delete from tablespaceinfo --清空数据表
: {* Q5 K1 U; h) i* H6 Z: n9 l 9 f7 s6 y6 x/ n9 F/ D2 M% n/ J declare @tablename varchar(255) --表名称
V$ C& u& G$ Q! w, L/ J' O/ k : Z( b8 T4 @5 B5 a; i declare @cmdsql varchar(500)
4 W3 _, L# L; F8 q( ~( W J% j5 r. E, x' V DECLARE Info_cursor CURSOR FOR
% |, _) c/ l+ Y) p$ T0 O select o.name
$ g9 c; ~) Q/ |" v from dbo.sysobjects o where OBJECTPROPERTY(o.id, N'IsTable') = 1
1 ?5 p) X& B( d" z6 C J and o.name not like N'#%%' order by o.name
# b, J1 ^* ]6 [ , A; F1 u+ @$ Y# n! {+ ] a/ i/ w OPEN Info_cursor
. ?9 |7 x; _2 c+ K2 ]. S4 \ k3 @/ H8 C f. m) U FETCH NEXT FROM Info_cursor
1 T+ d- U- U D! J! K+ g! i INTO @tablename
* t7 I' M+ s e9 t- r 0 t3 y* A% q* {, j! I) Y4 e/ m WHILE @@FETCH_STATUS = 0
/ X1 L/ _$ L7 j2 Q BEGIN
; a$ p* @) ]$ Z$ \6 N3 _, O 0 C) E# b6 V5 x: a1 {; I) H if exists (select * from dbo.sysobjects where id = object_id(@tablename) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
+ x0 P) `& A8 F. f execute sp_executesql
+ S% ?9 T' Z" _, C N'insert into tablespaceinfo exec sp_spaceused @tbname',
9 p h4 n) g0 L% i: ? N'@tbname varchar(255)',
) n( _! ?5 g% }4 b0 }6 n, c @tbname = @tablename
/ V$ b3 f0 q. i3 I/ ~ * @" Q# O4 o0 P6 ]) s" U3 i FETCH NEXT FROM Info_cursor
" z% K3 O3 D$ n) J; A4 k+ p% X INTO @tablename
2 a, w* c- b' o END
. r! Q4 {( O) \ 2 \: [4 R* b6 P* Q) z$ Q7 B' K ?9 a2 l CLOSE Info_cursor
" L$ l9 f4 H p7 [& f9 [8 z$ Y DEALLOCATE Info_cursor
P4 U/ H% M7 e1 U8 v* a. B GO
+ x! `/ L+ l4 q7 M9 Q. F4 m9 B * k* S8 B: \# R0 n1 H9 E 执行存储过程
; o' F) N2 B& b% `8 K8 Q : z$ h1 y8 |2 l, q( v& y( ~/ M$ y exec get_tableinfo
9 [! J0 Z) U( r9 d5 ^- y * A, h- `1 K/ N/ i; \ U, { 查询运行该存储过程后得到的结果
" ~% O5 Q$ p( N+ I; z ' @, R3 b6 M8 |% o8 @ select *
" x) R3 A8 Q8 |3 d) W' E8 \. S from tablespaceinfo
: p+ S, ~! T" S8 D order by cast(left(ltrim(rtrim(reserved)) , len(ltrim(rtrim(reserved)))-2) as int) desc
* C6 A. s3 a' r4 I2 }+ X $ g+ Y; ~4 s* w8 y