USE [VeritabaniAdi];  -- 🔄 Burayı kendi veritabanı adınla değiştir
GO

DECLARE @TableName NVARCHAR(255);
DECLARE @IndexName NVARCHAR(255);
DECLARE @SchemaName NVARCHAR(255);
DECLARE @SQL NVARCHAR(MAX);

DECLARE index_cursor CURSOR FOR
SELECT 
    s.name AS SchemaName,
    t.name AS TableName,
    i.name AS IndexName,
    ips.avg_fragmentation_in_percent,
    ips.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') AS ips
INNER JOIN sys.indexes AS i ON ips.object_id = i.object_id AND ips.index_id = i.index_id
INNER JOIN sys.tables AS t ON i.object_id = t.object_id
INNER JOIN sys.schemas AS s ON t.schema_id = s.schema_id
WHERE ips.page_count > 100 
  AND i.type_desc IN ('CLUSTERED', 'NONCLUSTERED') 
  AND i.name IS NOT NULL
ORDER BY ips.avg_fragmentation_in_percent DESC;

OPEN index_cursor;
FETCH NEXT FROM index_cursor INTO @SchemaName, @TableName, @IndexName, @SQL, @SQL;

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Fragmentation oranına göre karar ver
    IF @SQL BETWEEN 5 AND 30
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON [' + @SchemaName + '].[' + @TableName + '] REORGANIZE;';
    END
    ELSE IF @SQL > 30
    BEGIN
        SET @SQL = 'ALTER INDEX [' + @IndexName + '] ON [' + @SchemaName + '].[' + @TableName + '] REBUILD WITH (FILLFACTOR = 90);';
    END
    ELSE
    BEGIN
        -- %5 altıysa işlem yapma
        SET @SQL = NULL;
    END

    IF @SQL IS NOT NULL
    BEGIN
        PRINT '-- Executing: ' + @SQL;
        EXEC (@SQL);
    END

    FETCH NEXT FROM index_cursor INTO @SchemaName, @TableName, @IndexName, @SQL, @SQL;
END

CLOSE index_cursor;
DEALLOCATE index_cursor;
