Thursday, 4 February 2010

SQL Code: Object Location Within Data Files

I'm doing a lot of playing around with different numbers of data files and performance right now and in doing that I'm moving data around files and filegroups alot.
One of the things I find maddening is when I *think* I've moved all the data only to find that a filegroup still isn't empty. You check tables, indexes, indexed views, heaps, all look like they're in the right spot. That's why I wrote the query below. It will show exactly what data is where in your database. It's helpful for tracking down LOB_DATA that doesn't move with the rest of your table data :)

SELECT
OBJECT_NAME(object_id) AS obj_name
,p.rows
,au.type_desc
,au.used_pages
,au.data_space_id
,mf.name AS [file_name]
,mf.physical_name
,mf.state_desc
FROM sys.partitions p
JOIN sys.allocation_units au
ON p.partition_id = au.container_id
JOIN sys.master_files mf
ON au.data_space_id = mf.data_space_id
AND mf.database_id = DB_ID()
ORDER BY obj_name, au.data_space_id;

No comments: