我的团队正在开发一个.NET Web应用程序,其数据存储通过SQL Server 2005 Express进行管理。是否可以自动执行数据库中的任务,以便在部署/安装后的一段时间内自动重建某些索引?如果是这样,这是如何实现的?我认为数据库会在tasks
之下,但我没有看到它。
答案 0 :(得分:0)
当我为数据库提供服务时,此脚本可帮助我删除索引的碎片。也许,它对你有用:
SET NOCOUNT ON;
DECLARE
@SQL NVARCHAR(MAX)
, @IndexName SYSNAME
, @Output VARCHAR(200)
, @ServerVersion VARCHAR(100)
SELECT @ServerVersion = CAST(SERVERPROPERTY('Edition') AS VARCHAR(100))
DECLARE cur CURSOR LOCAL READ_ONLY FORWARD_ONLY FOR
SELECT
'ALTER INDEX [' + ix.name + N'] ON [' + SCHEMA_NAME(t.[schema_id]) + '].[' + t.name + '] ' +
CASE
WHEN ps.avg_fragmentation_in_percent > 50 THEN
CASE WHEN @ServerVersion LIKE 'Enterprise%' OR @ServerVersion LIKE 'Developer%' THEN
'REBUILD WITH (SORT_IN_TEMPDB = ON, ONLINE = ON ' + CASE WHEN ix.fill_factor > 0 THEN ', FILLFACTOR = ' + CAST(ix.fill_factor AS VARCHAR(3)) ELSE '' END + ') '
ELSE
'REBUILD WITH (SORT_IN_TEMPDB = ON' + CASE WHEN ix.fill_factor > 0 THEN ', FILLFACTOR = ' + CAST(ix.fill_factor AS VARCHAR(3)) ELSE '' END + ') '
END
ELSE 'REORGANIZE '
END +
CASE
WHEN ps.partition_number > 1 THEN N' PARTITION = ' + CAST(ps.partition_number AS NVARCHAR(MAX))
ELSE N''
END + ';', ix.name
FROM sys.indexes ix
JOIN sys.objects t ON t.[object_id] = ix.[object_id]
JOIN (
SELECT
[object_id]
, index_id
, avg_fragmentation_in_percent
, partition_number
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, N'LIMITED')
WHERE page_count > 100
AND avg_fragmentation_in_percent > 10
) ps ON t.[object_id] = ps.[object_id] AND ix.index_id = ps.index_id
OPEN cur
FETCH NEXT FROM cur INTO @SQL, @IndexName
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @Output = CONVERT(NVARCHAR(15), GETDATE(), 114) + ': ' + @IndexName
RAISERROR(@Output, 0, 1) WITH NOWAIT
EXEC (@SQL)
FETCH NEXT FROM cur INTO @SQL, @IndexName
END
CLOSE cur
DEALLOCATE cur