Wednesday, December 22, 2010

How to create a SQL trace using T-SQL

Some users want to know if there is a way to monitor events on SQL server without using SQL Profiler. Yes, there is: the engine support behind SQL Profiler is the feature called SQL Trace which is introduced in SQL 2005. SQL Trace provides a set of stored procedures to create traces on an instance of the SQL Server Database Engine. These system stored procedures can be used from within user's own applications to create traces manually, and allows to write custom applications specific to their needs.

The following sample code shows how to create customized SQL trace to monitor events to user's interest

-- sys.traces shows the existing sql traces on the server 
SELECT * FROM sys.traces 
go
--create a new trace, make sure the @tracefile must NOT exist on the disk yet 
DECLARE @tracefile NVARCHAR(500) SET @tracefile=N'c:\temp\newtraceFile'
DECLARE @trace_id INT
DECLARE @maxsize BIGINT
SET @maxsize =1
EXEC sp_trace_create @trace_id OUTPUT,2,@tracefile ,@maxsize 
go
--- add the events of insterest to be traced, and add the result columns of interest
--  Note: look up in sys.traces to find the @trace_id, here assuming this is the first trace in the server, therefor @trace_id=1
DECLARE @trace_id INT = 1, @on BIT = 1, @current_num INT
SET @current_num =1
WHILE(@current_num <65)
BEGIN
	--add events to be traced, id 14 is the login event, you add other events per your own requirements, the event id can be found @ BOL http://msdn.microsoft.com/en-us/library/ms186265.aspx
	EXEC sp_trace_setevent @trace_id,14, @current_num,@on
	SET @current_num=@current_num+1
END 
go
 
--turn on the trace: status=1
-- use sys.traces to find the @trace_id, here assuming this is the first trace in the server, so @trace_id=1 
DECLARE @trace_id INT
SET @trace_id=1
EXEC sp_trace_setstatus  @trace_id,1
 
--pivot the traced event
SELECT LoginName,DatabaseName,* FROM ::FN_TRACE_GETTABLE(N'c:\temp\newtraceFile.trc',DEFAULT)
go
 
-- stop trace. Please manually delete the trace file on the disk
-- use sys.traces to find the @trace_id, here assuming this is the first trace in the server, so @trace_id=1 
DECLARE @trace_id INT
SET @trace_id=1
EXEC sp_trace_setstatus @trace_id,0 
EXEC sp_trace_setstatus @trace_id,2 
go

Thursday, December 9, 2010

Find Best Clustered Index

The following query will compare the nonclustered indexes vs the clustered index and determine which index would qualify as the best clustered index based upon the DMV statistics.

If a clustered index does not exist on the table, it will also suggest one of the existing nonclustered indexes as the clustered index.

DECLARE @NonClusteredSeekPct float 
DECLARE @ClusteredLookupFromNCPct float 
-- Define percentage of usage the non clustered should  
-- receive over the clustered index  
SET @NonClusteredSeekPct = 1.50
 -- 150%  
-- Define the percentage of all lookups on the clustered index  
-- should be executed by this non clustered index  
SET @ClusteredLookupFromNCPct = .75 -- 75%  
SELECT  TableName = object_name(idx.object_id)
       ,NonUsefulClusteredIndex = idx.NAME
       ,ShouldBeClustered = nc.NonClusteredName
       ,Clustered_User_Seeks = c.user_seeks
       ,NonClustered_User_Seeks = nc.user_seeks
       ,Clustered_User_Lookups = c.user_lookups
       ,DatabaseName = db_name(c.database_id)
FROM    sys.indexes idx
LEFT JOIN sys.dm_db_index_usage_stats c ON idx.object_id = c.object_id
                                           AND idx.index_id = c.index_id  
--AND c.database_id = @DBID  
JOIN    ( SELECT    idx.object_id
                   ,nonclusteredname = idx.NAME
                   ,ius.user_seeks
          FROM      sys.indexes idx
          JOIN      sys.dm_db_index_usage_stats ius ON idx.object_id = ius.object_id
                                                       AND idx.index_id = ius.index_id
          WHERE     idx.type_desc = 'nonclustered'
                    AND ius.user_seeks = ( SELECT   MAX(user_seeks)
                                           FROM     sys.dm_db_index_usage_stats
                                           WHERE    object_id = ius.object_id
                                                    AND type_desc = 'nonclustered' )
          GROUP BY  idx.object_id
                   ,idx.NAME
                   ,ius.user_seeks ) nc ON nc.object_id = idx.object_id
WHERE   idx.type_desc IN ( 'clustered', 'heap' )  
-- non clustered user seeks outweigh clustered by 150%  
        AND nc.user_seeks > ( c.user_seeks * @NonClusteredSeekPct )  
-- nc index usage is primary cause of clustered lookups 80%  
        AND nc.user_seeks >= ( c.user_lookups * @ClusteredLookupFromNCPct )
ORDER BY nc.user_seeks DESC 

Wednesday, December 8, 2010

Find Table without Clustered Index / Primary Key

One of the basic Database Rule I have is that all the table must Clustered Index. Clustered Index speeds up performance of the query ran on that table. Clustered Index are usually Primary Key but not necessarily.

SELECT OBJECT_NAME(i.OBJECT_ID) AS tableName, rows
FROM sys.indexes i
INNER JOIN sys.partitions p ON i.object_id = p.object_id AND i.index_id = p.index_id
WHERE i.INDEX_ID = 0
AND OBJECTPROPERTY(i.OBJECT_ID,'IsUserTable') = 1
ORDER BY 2 DESC 
 

Using TRY...CATCH to Rollback a Transaction in case of an error

As you all might know, one of the downsides of the @@ERROR variable approach  to catch the  error is that we must check the value of this variable after each and every DML /DDL  statement to determine if an error occurred and, if so, to rollback the transaction. With SQL Server 2005's TRY...CATCH block, however, these types of scripts are greatly simplified.

 

BEGIN TRAN
BEGIN TRY
    SELECT  1 / 0 infinite
    COMMIT TRAN
END TRY
BEGIN CATCH
    RAISERROR ( 'err', 16, 1 )
    SELECT  @@trancount before
    ROLLBACK TRAN
    SELECT  @@trancount after
END CATCH
GO 


Does the order in which we put BEGIN TRAN..BEGIN TRY matters , let us check



 



BEGIN TRY 
BEGIN TRAN 
    SELECT  1 / 0 infinite
COMMIT TRAN
END TRY
BEGIN CATCH
    RAISERROR ( 'err', 16, 1 )
    SELECT  @@trancount before
    ROLLBACK TRAN
    SELECT  @@trancount after
END CATCH
GO