-- SQL Server 性能优化配置

-- 启用即时文件初始化（需要重启服务）
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
PRINT '高级选项已启用';

-- 配置最大内存使用量（根据容器内存限制调整）
-- 这里设置为4GB，可以根据实际需要调整
EXEC sp_configure 'max server memory (MB)', 4096;
RECONFIGURE;
PRINT '最大内存设置为 4GB';

-- 配置最大并行度（根据CPU核心数调整）
EXEC sp_configure 'max degree of parallelism', 4;
RECONFIGURE;
PRINT '最大并行度设置为 4';

-- 启用查询存储（SQL Server 2016+）
USE SampleDB;
GO

-- 启用查询存储
ALTER DATABASE SampleDB SET QUERY_STORE = ON;
ALTER DATABASE SampleDB SET QUERY_STORE (
    OPERATION_MODE = READ_WRITE,
    CLEANUP_POLICY = (STALE_QUERY_THRESHOLD_DAYS = 30),
    DATA_FLUSH_INTERVAL_SECONDS = 900,
    INTERVAL_LENGTH_MINUTES = 60,
    MAX_STORAGE_SIZE_MB = 1000,
    QUERY_CAPTURE_MODE = AUTO,
    SIZE_BASED_CLEANUP_MODE = AUTO
);
PRINT '查询存储已启用';

-- 创建性能监控视图
USE SampleDB;
GO

IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'PerformanceStats')
BEGIN
    EXEC('
    CREATE VIEW PerformanceStats AS
    SELECT 
        GETDATE() AS CheckTime,
        (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_process = 1) AS ActiveConnections,
        (SELECT COUNT(*) FROM sys.dm_exec_requests WHERE status IN (''running'', ''runnable'', ''suspended'')) AS ActiveRequests,
        (SELECT SUM(pages_kb) FROM sys.dm_os_memory_clerks WHERE type = ''MEMORYCLERK_SQLBUFFERPOOL'') / 1024 AS BufferPoolMB
    ');
    PRINT '性能监控视图创建成功';
END
ELSE
BEGIN
    PRINT '性能监控视图已存在';
END
GO

PRINT '性能优化配置完成！';
