When you use Microsoft SQL Server Management Studio (SSMS) to run an SQL query that returns a large amount of data, you receive an error message that resembles the following:

“An error occurred while executing batch. Error message is: Exception of type ‘System.OutOfMemoryException’ was thrown”
This issue occurs because SSMS has insufficient memory to allocate for large results. How to manage it?

To work around this issue, try one of the following methods.

Method 1: Output the results as text

Configure the query window to output the query results as text. A text output uses less memory than the grid, and it may be sufficient to display the query results. To make this change, follow these steps:

  1. Right-click the query window.
  2. Click Results to.
  3. Click Results to Text.

Method 2: Output the results to a file

Configure the query window to output the query results to a file. A file output uses a minimal amount of memory. This reserves more memory for storing the results set. To make this change, follow these steps:

  1. Right-click the query window.
  2. Click Results to.
  3. Click Results To File.
  4. Run the query, and then select the location in which to save the results file.

Method 3: Use sqlcmd (see this post)

Use the sqlcmd tool instead of SSMS to run the SQL queries. This method enables queries to be run without the resources that are required by the SSMS UI. Additionally, you can use the 64-bit version of Sqlcmd.exe to avoid the memory restriction that affects the 32-bit SSMS process.

Advertisements