2025年12月1日 星期一

[研究]3xx MB 的 .sql 用SSMS匯入 SQL Server (32 GB) 出現記憶體不足

[研究]3xx MB 的 .sql 用SSMS匯入 SQL Server (32 GB) 出現記憶體不足

2025-12-01


Microsoft SQL Server Management Studio

無法執行指令碼。

其他资讯:

Insufficient memory to continue the execution of the program. (mscorlib)

省複製 顯示詳細資料 確定



Insufficient memory to continue the execution of the program. (mscorlib)

程式位置:

System Runtime InteropServices.Marshal.AllocCo.TaskMem(Int32 cb)

Microsoft.SqUerver Management UI UI VSIntegration Shell TexEutfer.GetText(Unt32 startPostion, Int32 chars)

Microsoft SolServer Management UI YSInte gration Shell TextBuffer.get Text)

Micoosoft.SqlServer Management UI.UI.YSIntegration ShellCode WundowControl GetSelected TextSpen)

Microsoft.So Server.Management UI VSInte gration Edidors ScriptidorControl GetSelected TextSpan)

R Miczoout SoNerver Management Ul USIntegrateshon EdiScopthondReiptAndResmlbaditorContol OnExExecSonpt(Obect sendes, Eventkra)

**********

ChatGPT


你遇到的錯誤是 SSMS 在匯入大型 .sql 檔案時出現的記憶體不足 (Insufficient memory),即使你電腦有 32 GB RAM,也可能發生,原因和背景如下:


1️⃣ SSMS 與大型 SQL 檔案的限制

  • SSMS 是以 .NET Framework 開發的桌面程式。
  • SSMS 的 32 位元或 64 位元程式記憶體管理有限制:
    • 32-bit SSMS 會受限於 2–4 GB 的最大可用記憶體。
    • 即使是 64-bit SSMS,也可能因 單個物件在記憶體中的分配而遇到限制。
  • 當你用 SSMS 打開並執行大型 .sql 文件 (幾百 MB):
    • SSMS 會 先把整個檔案讀入記憶體。
    • 若檔案內容龐大,尤其有大量 INSERT 語句,會瞬間消耗大量記憶體。
    • 這會觸發 .NET mscorlib 的 “Insufficient memory” 錯誤。

2️⃣ 其他潛在因素

  • SSMS 版本過舊:早期版本在處理大檔案時記憶體管理不佳。
  • 單行語句過長:.sql 裡的 INSERT 語句或資料列非常長,可能導致暫存物件占用超大記憶體。
  • Windows 記憶體碎片或其他程式佔用:即使總 RAM 足夠,連續大記憶體區塊可能不足。


3️⃣ 解決方案 / 替代方法


  • 用 SQLCMD 匯入(推薦)

sqlcmd -S <ServerName> -d <DatabaseName> -U <User> -P <Password> -i "C:\path\to\file.sql"


    • SQLCMD 是命令列工具,不會一次把整個檔案載入記憶體。
    • 對大檔案 (百 MB ~ GB) 很穩定。

  • 分割 SQL 檔案

    • 用文字編輯器或專用工具把 3xx MB 的檔案拆成多個小檔案,每個 50~100 MB 執行一次。
    • 避免一次塞入 SSMS 記憶體。
  • 改用批次 INSERT 或 BCP

    • 若檔案是大量 INSERT 資料,可以改成 CSV + BULK INSERT 或 BCP 工具匯入。
    • 效能更好,對大型資料庫匯入更穩定。
  • 使用最新 64-bit SSMS
    • 確認你安裝 SSMS 18+ 或 19+ 64-bit 版本。
    • 舊版 32-bit SSMS 很容易在大檔案時爆記憶體。


💡 重點結論

  • 問題不是你 RAM 不夠,而是 SSMS 將整個檔案載入記憶體 的方式與 .NET 記憶體限制。
  • 對於幾百 MB 的 .sql,最好不要用 SSMS GUI,改用 SQLCMD 或分割檔案。

(完)



沒有留言:

張貼留言