Happy Monday! One thing I’m planning to do with this blog is post useful scripts that I’ve written to hopefully make your life easier as a DBA. Nothing complex and scary, plus I hope to explain any of the particular tricks within the script so you can build upon them to fit your specific situation.
As DBA’s, we’re commonly called upon to manage the space on our servers. Usually this is just a matter of managing data files, the free space within those files, and the total space on the drives. However, there are times we need more detail. Today’s script is one I put together to use sp_spaceused, which is a stored procedure provided with SQL server to give you space information on specific objects (databases and tables, typically). It’s very handy for analyzing your tables for consumption.
The problem I ran into with the stored procedure is that it would just show one table at a time, and often I need to see all the tables in a database relative to each other. So this script is a simple cursor that executes dynamic SQL and gets all the space details for all your user tables for the current database context.
/*Create return table.*/ declare @return table (name varchar(100), rows bigint, reserved varchar(30), data varchar(30), index_size varchar(30), unused varchar(30)) /*Store current table.*/ declare @curr varchar(100) /*Create cursor for all tables.*/ declare recscan cursor for select name from sysobjects where type = 'U' /*Use cursor to run sp_spaceused on all tables.*/ open recscan fetch next from recscan into @curr while @@fetch_status = 0 begin insert into @return exec sp_spaceused @curr fetch next from recscan into @curr end /*Clean up cursor.*/ close recscan deallocate recscan /*return data*/ select name, rows, reserved, data, index_size, unused from @return order by convert(bigint,left(reserved,len(reserved)-3)) desc
(You can download the script here.)
The only real gotchas to keep in mind is that the size values are returned as strings and the values are in kilobytes. If you need to modify them for readability/sorting, you’ll need a bit of string manipulation. See the ORDER BY clause for how I handle that.
You can also get this information from the DMVs in SQL Server. I plan on covering that in a later post. Until then, this script should take care of most of your needs and give you some additional insight into your databases.