在优化前需明确内存占用现状,通过以下DMV查询关键指标:
SELECT total_physical_memory_kb/1024 AS Total_Memory_MB, available_physical_memory_kb/1024 AS Available_Memory_MB FROM sys.dm_os_sys_memory;SELECT d.name AS Database_Name, SUM(a.total_pages)*8/1024 AS Memory_Usage_MB FROM sys.dm_os_memory_clerks a JOIN sys.databases d ON a.database_id = d.database_id GROUP BY d.name ORDER BY Memory_Usage_MB DESC;SELECT counter_name AS [指标], cntr_value AS [值(KB)] FROM sys.dm_os_performance_counters WHERE counter_name IN ('Target Server Memory (KB)', 'Total Server Memory (KB)', 'Page life expectancy');Page life expectancy(页生命周期)<60秒表明内存压力大,需及时优化。关键参数:max server memory(最大服务器内存)与min server memory(最小服务器内存)
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'max server memory (MB)', 24576; -- 24GB
RECONFIGURE;
EXEC sp_configure 'min server memory (MB)', 4096; -- 4GB
RECONFIGURE;
max server memory与min server memory设为相同值(会禁用动态内存调整,影响性能弹性);SELECT *(只查询必要字段);使用EXPLAIN分析执行计划,识别高成本操作(如全表扫描)。WHERE、JOIN、ORDER BY字段创建索引(如聚集索引、非聚集索引),减少数据扫描量;定期检查索引碎片率(avg_fragmentation_in_percent > 30%需重建):-- 检查碎片率
SELECT index_id, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'DETAILED')
WHERE avg_fragmentation_in_percent > 30;
-- 重建碎片率高的索引
ALTER INDEX [索引名] ON [表名] REBUILD;
在内存紧张时,可通过以下命令清理缓存(生产环境谨慎使用,可能引发短期性能波动):
DBCC FREEPROCCACHE;DBCC DROPCLEANBUFFERS;DBCC FREEPROCCACHE; DBCC DROPCLEANBUFFERS;DECLARE @TargetMemory DECIMAL(19,2), @TotalMemory DECIMAL(19,2), @UseMemoryPercent DECIMAL(19,2);
SELECT @TargetMemory = cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Target Server Memory (KB)';
SELECT @TotalMemory = cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Total Server Memory (KB)';
SET @UseMemoryPercent = @TotalMemory / @TargetMemory;
IF @UseMemoryPercent > 0.1 -- 若内存使用率超过10%
BEGIN
DBCC FREEPROCCACHE;
DBCC DROPCLEANBUFFERS;
WAITFOR DELAY '00:01:30'; -- 等待1.5分钟
-- 重新设置max server memory(先调小再调回)
EXEC sp_configure 'max server memory', 10000; -- 临时设置为10GB
RECONFIGURE;
WAITFOR DELAY '00:01:30';
EXEC sp_configure 'max server memory', 24576; -- 调回24GB
RECONFIGURE;
END
```。
DBCC MEMORYSTATUS;输出缓冲池、计划缓存等详细信息,定期检查内存分配状态;监控内存等待事件(SELECT * FROM sys.dm_os_wait_stats WHERE wait_type LIKE '%MEMORY%'),识别内存瓶颈。