Saturday, December 7, 2013

How to Get total no of rows for all table in a database

DECLARE @SpaceDetails as table

(name varchar(100),Totalnumberofrows int,ReservedSpace varchar(100),allocatedspace varchar(100),indexsize varchar(100),unusedspace varchar(100))

insert into @SpaceDetails

EXEC sys.sp_MSforeachtable 'sp_spaceused ''?'''

-- to fecth total nof of rows for each table

select * from @SpaceDetails

--below query shows total no of rows in all tables

select SUM(Totalnumberofrows) AS 'Total number of rows',

CAST((SUM (CAST((SUBSTRING(ReservedSpace,1,charindex(' ',ReservedSpace))) AS FLOAT))/1024) AS VARCHAR)+' '+'MB' as 'total ReservedSpace size' ,

CAST((SUM (CAST((SUBSTRING(allocatedspace,1,charindex(' ',allocatedspace))) AS FLOAT))/1024) AS VARCHAR)+' '+'MB' as 'total allocatedspace size' ,

CAST((SUM (CAST((SUBSTRING(indexsize,1,charindex(' ',indexsize))) AS FLOAT))/1024) AS VARCHAR)+' '+'MB' as 'total indexsize size' ,

CAST((SUM (CAST((SUBSTRING(unusedspace,1,charindex(' ',unusedspace))) AS FLOAT))/1024) AS VARCHAR)+' '+'MB' as 'total unusedspace size'

from @SpaceDetails


No comments: