Thursday, 24 May 2012

SQL Server - Query to get table sizes

Once again I am posting SQL that I have found on the internet (mainly so that I have can find this scriopt easily in the future).  This one is thanks to marc_s and can be found in this Stackoverflow post.  The script will give you a breakdown of the table size for each table in your database.  This includes a row count, disk space used and disk space available.  I have modified the original script slightly as a number of databases I work with have multiple schemas and the original script doesn't show the schema name.

SELECT
    s.NAME AS SchemaName,  
    t.NAME AS TableName, 
    p.rows AS RowCounts, 
    SUM(a.total_pages) * 8 AS TotalSpaceKB,  
    SUM(a.used_pages) * 8 AS UsedSpaceKB,  
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB 
FROM  sys.tables t 
INNER JOIN sys.Schemas s ON t.schema_id = s.schema_id
INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id 
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id 
INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id 
WHERE  
    t.NAME NOT LIKE 'dt%'  
    AND t.is_ms_shipped = 0 
    AND i.OBJECT_ID > 255  
GROUP BY
 s.Name,  
    t.Name, 
    p.[Rows] 
ORDER BY  
 s.Name,
    t.Name 

Wednesday, 16 May 2012

T-SQL script for finding object dependencies

This morning I wanted to find out where a specific stored procedure was being used.  I wasn't sure how to do this using T-SQL so did a bit of googling and found this article.  I have made a slight enhancement to the scripts shown in the article. 

DECLARE @ObjectName VARCHAR(500)
SET @ObjectName = 'dbo.sp_test_Proc'

-- shows objects that the named object depends on
SELECT DISTINCT OBJECT_NAME(DEPID) DEPENDENT_ON_OBJECT, OBJECT_NAME (ID) OBJECTNAME
FROM SYS.SYSDEPENDS
WHERE ID = OBJECT_ID(@ObjectName)

-- shows objects that use the named object
SELECT DISTINCT  OBJECT_NAME(DEPID) OBJECT_NAME, OBJECT_NAME (ID) USED_IN_OBJECT
FROM SYS.SYSDEPENDS
WHERE DEPID = OBJECT_ID(@ObjectName)

I am sure I will get a lot of milage out of this in the future.