31 Mart 2018 Cumartesi

SQL Server Refresh All View

SET NOCOUNT ON
DECLARE @SQL varchar(max) = ''
SELECT @SQL = @SQL + 'print ''Refreshing --> ' + name + '''
EXEC sp_refreshview ' + name + ';
'
  FROM sysobjects
  WHERE type = 'V' --< condition to select all views, may vary by your standards
--SELECT @SQL
EXEC(@SQL)

10 Mart 2018 Cumartesi

SQL server long running queries query stats

SELECT TOP 100
    qs.total_elapsed_time / qs.execution_count / 1000000.0 AS average_seconds,
    qs.total_elapsed_time / 1000000.0 AS total_seconds,
    qs.execution_count,
    SUBSTRING (qt.text,qs.statement_start_offset/2,
         (CASE WHEN qs.statement_end_offset = -1
            THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
          ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS individual_query,
    o.name AS object_name,
    DB_NAME(qt.dbid) AS database_name
  FROM sys.dm_exec_query_stats qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
    LEFT OUTER JOIN sys.objects o ON qt.objectid = o.object_id
where qt.dbid = DB_ID()
  ORDER BY average_seconds DESC;

SQL Server unused indexes

select object_name(i.object_id) as ObjectName, i.name as [Unused Index],MAX(p.rows) Rows
,8 * SUM(a.used_pages) AS 'Indexsize(KB)',
case
when i.type = 0 then 'Heap'
when i.type= 1 then 'clustered'
when i.type=2 then 'Non-clustered' 
when i.type=3 then 'XML' 
when i.type=4 then 'Spatial'
when i.type=5 then 'Clustered xVelocity memory optimized columnstore index' 
when i.type=6 then 'Nonclustered columnstore index'
end index_type,
'DROP INDEX ' + i.name + ' ON ' + object_name(i.object_id) 'Drop Statement'
from sys.indexes i
left join sys.dm_db_index_usage_stats s on s.object_id = i.object_id
     and i.index_id = s.index_id
     and s.database_id = db_id()
JOIN sys.partitions AS p ON p.OBJECT_ID = i.OBJECT_ID AND p.index_id = i.index_id
JOIN sys.allocation_units AS a ON a.container_id = p.partition_id
where objectproperty(i.object_id, 'IsIndexable') = 1
AND objectproperty(i.object_id, 'IsIndexed') = 1
and s.index_id is null -- and dm_db_index_usage_stats has no reference to this index
or (s.user_updates > 0 and s.user_seeks = 0 and s.user_scans = 0 and s.user_lookups = 0)-- index is being updated, but not used by seeks/scans/lookups
GROUP BY object_name(i.object_id) ,i.name,i.type
order by object_name(i.object_id) asc