用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - sql代码库

获取数据表的磁盘占用大小和行数

2017-05-16 作者: 小章举报

[sql]代码库

BEGIN TRY
	SELECT a3.NAME AS [schemaname]
		,a2.NAME AS [tablename]
		,a1.rows AS row_count
		,(a1.reserved + ISNULL(a4.reserved, 0)) * 8 AS reserved
		,a1.data * 8 AS data
		,(
			CASE 
				WHEN (a1.used + ISNULL(a4.used, 0)) > a1.data
					THEN (a1.used + ISNULL(a4.used, 0)) - a1.data
				ELSE 0
				END
			) * 8 AS index_size
		,(
			CASE 
				WHEN (a1.reserved + ISNULL(a4.reserved, 0)) > a1.used
					THEN (a1.reserved + ISNULL(a4.reserved, 0)) - a1.used
				ELSE 0
				END
			) * 8 AS unused
		,CASE 
			WHEN a1.data = 0
				THEN 0
			ELSE (
					CASE 
						WHEN (a1.reserved + ISNULL(a4.reserved, 0)) > a1.used
							THEN (a1.reserved + ISNULL(a4.reserved, 0)) - a1.used
						ELSE 0
						END
					) * 10000 / (a1.reserved + ISNULL(a4.reserved, 0))
			END unusedRate
	FROM (
		SELECT ps.object_id
			,SUM(CASE 
					WHEN (ps.index_id < 2)
						THEN row_count
					ELSE 0
					END) AS [rows]
			,SUM(ps.reserved_page_count) AS reserved
			,SUM(CASE 
					WHEN (ps.index_id < 2)
						THEN (ps.in_row_data_page_count + ps.lob_used_page_count + ps.row_overflow_used_page_count)
					ELSE (ps.lob_used_page_count + ps.row_overflow_used_page_count)
					END) AS data
			,SUM(ps.used_page_count) AS used
		FROM sys.dm_db_partition_stats ps
		GROUP BY ps.object_id
		) AS a1
	LEFT OUTER JOIN (
		SELECT it.parent_id
			,SUM(ps.reserved_page_count) AS reserved
			,SUM(ps.used_page_count) AS used
		FROM sys.dm_db_partition_stats ps
		INNER JOIN sys.internal_tables it ON (it.object_id = ps.object_id)
		WHERE it.internal_type IN (
				202
				,204
				)
		GROUP BY it.parent_id
		) AS a4 ON (a4.parent_id = a1.object_id)
	INNER JOIN sys.all_objects a2 ON (a1.object_id = a2.object_id)
	INNER JOIN sys.schemas a3 ON (a2.schema_id = a3.schema_id)
	WHERE a2.type <> N'S'
		AND a2.type <> N'IT'
	ORDER BY unusedRate DESC
END TRY
 
BEGIN CATCH
	SELECT - 100 AS l1
		,1 AS schemaname
		,ERROR_NUMBER() AS tablename
		,ERROR_SEVERITY() AS row_count
		,ERROR_STATE() AS reserved
		,ERROR_MESSAGE() AS data
		,1 AS index_size
		,1 AS unused
END CATCH    


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...