sqlserver內存釋放

字號:


    注:本人在用sqlserver2000測試 ,很多命令都不能用
    由于sql server對于系統(tǒng)內存的管理策略是有多少占多少,除非系統(tǒng)內存不夠用了(大約到剩余內存為4m左右),
    sql server才會釋放一點點內存。所以很多時候,我們會發(fā)現(xiàn)運行sql server的系統(tǒng)內存往往居高不下。
    這些內存一般都是sql server運行時候用作緩存的,例如你運行一個select語句,
    那么sql server會將相關的數(shù)據(jù)頁(sql server操作的數(shù)據(jù)都是以頁為單位的)加載到內存中來,
    下一次如果再次請求此頁的數(shù)據(jù)的時候,就無需讀取磁盤了,大大提高了速度。這類的緩存叫做數(shù)據(jù)緩存。
    還有一些其他類型的緩存,如執(zhí)行存儲過程時,sql server需要先編譯再運行,編譯后的結果也會緩存起來,
    下一次就無需再次編譯了。如果這些緩存已經(jīng)不需要了,那么我們可以調用以下幾個dbcc管理命令來清理這些緩存:
    dbcc freeproccache
    dbcc freesessioncache
    dbcc freesystemcache('all')
    dbcc dropcleanbuffers
    這幾個命令分別用來清除存儲過程相關的緩存、會話緩存、系統(tǒng)緩存以及所有所有緩存
    但是需要注意的是,這幾個命令雖然會清除掉現(xiàn)有緩存,為新的緩存騰地方,
    但是sql server并不會因此釋放掉已經(jīng)占用的內存。無奈的是,sql server
    并沒有提供任何命令允許我們釋放不用到的內存。因此我們只能通過動態(tài)調整
    sql server可用的物理內存設置來強迫它釋放內存。
    我們也可以通過sql server management企業(yè)管理器進行動態(tài)控制。
    連接到企業(yè)管理器之后打開sql server實例的屬性面板,
    找到內存設置,改變其中的最大服務器內存使用即可
    --內存使用情況
    select * from sys.dm_os_performance_counters
    where counter_name in ('target server memory (kb)','total server memory (kb)')
    -- 內存狀態(tài)
    dbcc memorystatus
    --查看最小最大內存
    select
    cfg.name as [name],
    cfg.configuration_id as [number],
    cfg.minimum as [minimum],
    cfg.maximum as [maximum],
    cfg.is_dynamic as [dynamic],
    cfg.is_advanced as [advanced],
    cfg.value as [configvalue],
    cfg.value_in_use as [runvalue],
    cfg.description as [description]
    from
    sys.configurations as cfg
    --設置最小最大內存
    sp_configure 'show advanced options', 1
    go
    sp_configure 'min server memory', 0
    reconfigure
    go
    sp_configure 'max server memory', 2147483647
    reconfigure
    go
    sp_configure 'max server memory', 256
    reconfigure
    go
    sp_configure 'show advanced options', 0
    -----------------------------------------------------------------------------------------------
    create proc [dbo].reclaimmemory --強制釋放內存
    as
    begin
    dbcc freeproccache
    dbcc freesessioncache
    dbcc freesystemcache('all')
    dbcc dropcleanbuffers
    exec sp_configure 'max server memory', 256
    exec ('reconfigure' )
    waitfor delay '00:00:05'
    exec sp_configure 'max server memory', 2147483647
    exec ('reconfigure' )
    go
    end
    --使用示例
    /*
    reclaimmemory
    */