Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server Error 1087: Must Declare Table Variable

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

SQL Server Error 1087 occurs because a table variable is being referenced in a batch or scope where it has not been declared, or the declaration was separated from the usage by a batch separator (the GO command). To fix this, you must ensure that the DECLARE @TableName TABLE... statement and all queries using that variable are contained within a single execution batch without any GO commands between them.

What You'll Need

  • SQL Server Management Studio (SSMS) or Azure Data Studio.
  • A script containing the table variable causing the error.
  • Administrative or developer permissions to execute T-SQL scripts on the target database.

Step-by-Step

  1. Identify the Scope Boundary: Open your SQL script and look for the GO keyword. In SQL Server, GO is not a T-SQL command but a signal to the utility (like SSMS) to send the preceding block of code to the server as a single batch. Table variables are local to the batch in which they are declared. If you declare a variable in one batch and try to use it after a GO command, the second batch has no knowledge of the variable, triggering Error 1087.
  2. Locate the Declaration: Find the line where the table variable is defined. It should look like DECLARE @MyTableVariable TABLE (Column1 INT, Column2 VARCHAR(50));. Ensure this line is present and correctly spelled.
  3. Remove Intermediate Batch Separators: If you find a GO command between the DECLARE statement and the SELECT, INSERT, or UPDATE statement that uses the variable, delete the GO command. This merges the two blocks into one continuous batch, allowing the variable to remain in memory for the duration of the execution.
  4. Verify Variable Naming: Check for typos in the variable name. SQL Server is generally case-insensitive depending on your collation, but a misspelling (e.g., @UserTable vs @UsersTable) will cause the engine to think the variable was never declared.
  5. Check Dynamic SQL Scopes: If you are using EXEC sp_executesql or EXEC(), be aware that dynamic SQL runs in its own separate session scope. A table variable declared in the main script is not visible inside a dynamic SQL string. To fix this, you must either declare the table variable inside the dynamic string or pass the data using a Table-Valued Parameter (TVP).
  6. Execute as a Single Block: Highlight the entire section of code from the DECLARE statement down to the final usage of the variable and press F5 to execute. This ensures that no partial execution occurs, which would leave the variable undeclared in the current session state.

Common Mistakes

The most frequent mistake is the misuse of the GO command. Many developers use GO to organize their scripts visually or to separate logical steps, not realizing that it completely wipes the local variable stack. Once GO is encountered, every local variable (scalar or table) is dropped.

Another common error is attempting to use a table variable across different stored procedures. Table variables cannot be passed as output parameters in the traditional sense; they must be passed as Table-Valued Parameters. If you declare a table variable in Procedure A and expect it to be available in Procedure B without passing it explicitly, you will encounter a declaration error.

Developers also frequently confuse table variables (@Table) with temporary tables (#Table). Temporary tables are stored in tempdb and persist for the entire session (or until dropped), meaning they can survive a GO command. Table variables cannot. Switching to a temporary table is often the fastest fix for scripts that require multiple batches.

Tips

When working with large datasets, consider whether a table variable is the right choice. Table variables do not have distribution statistics, which can lead the SQL Server Query Optimizer to assume the table contains only one row. This can result in poor execution plans for large volumes of data. For larger sets, a local temporary table (#temp) is generally more performant because it supports indexes and statistics.

To keep your code clean while avoiding Error 1087, use comments (--) or whitespace to separate logical sections of your script instead of GO. This maintains the batch integrity while keeping the script readable.

If you find yourself needing the same table structure across multiple batches or procedures, create a User-Defined Table Type. This allows you to define the schema once at the database level and then declare variables of that type throughout your application, ensuring consistency and reducing declaration errors.

Troubleshooting

If you have removed the GO commands and are still seeing Error 1087, follow these steps in order:

First, check for conditional logic. If your DECLARE statement is wrapped inside an IF...ELSE block, ensure that the code attempting to use the variable is also within that same block or that the variable is declared outside the conditional logic. A variable declared inside an IF block is still available to the rest of the batch, but if the logic skips the declaration line entirely due to a failed condition, the subsequent usage will fail.

Second, examine your use of Dynamic SQL. If your code looks like EXEC('SELECT * FROM @MyTable'), it will always fail. The dynamic SQL engine cannot see the local scope of the calling batch. You must convert the table variable to a temporary table (#MyTable) because temporary tables are visible to nested dynamic SQL calls.

Third, verify that you are not accidentally executing the script in pieces. If you highlight only the SELECT statement and press execute, skipping the DECLARE line, SSMS will send only that fragment to the server. Since the server sees a request for a variable that wasn't declared in that specific request, it throws Error 1087. Always execute the declaration and the usage together.

Frequently Asked Questions

What is the difference between @table and #table?

A table variable (@table) exists only within the batch it is declared in and is cleaned up automatically. A temporary table (#table) is stored in tempdb and persists for the duration of the connection session, meaning it can be accessed across multiple GO commands.

Can I use a table variable in a View?

No, you cannot declare variables inside a View. Views must consist of a single SELECT statement. If you need temporary storage for a View, you should use a Common Table Expression (CTE) or a Table-Valued Function.

Why does my table variable cause slow performance?

Table variables lack statistics. The optimizer often estimates they have only one row, which can lead to nested loop joins where a hash join would be faster. For tables with more than a few hundred rows, use a temporary table instead.

Can I pass a table variable to a stored procedure?

Yes, but only by using a User-Defined Table Type. You must first create the type using CREATE TYPE, and then use that type as a READONLY parameter in your stored procedure definition.

Does dropping a table variable manually help?

You cannot manually DROP a table variable. They are automatically removed from memory when the batch finishes execution. Only temporary tables (#table) require or allow a DROP TABLE command.