SQL Server Error 167 occurs because you are attempting to create a formal index on a temporary object—specifically a table variable—using the CREATE INDEX statement. To fix this, you must define the index within the table variable's declaration using inline constraints (PRIMARY KEY or UNIQUE) rather than using a separate CREATE INDEX command after the table has been created.
In SQL Server, there is a fundamental difference between temporary tables (#TempTable) and table variables (@TableVariable). While you can use CREATE INDEX on a temporary table, you cannot do so on a table variable. The engine requires any indexing for table variables to be established at the moment of creation.
What You'll Need
- Access to SQL Server Management Studio (SSMS) or another SQL query editor.
- The T-SQL script that is currently triggering Error 167.
- Permissions to execute DDL (Data Definition Language) statements within your database context.
Step-by-Step
- Identify the Object Type: Look at the code triggering the error. Check if the object you are trying to index starts with an
@symbol (e.g.,@MyTable). If it does, it is a table variable, which is the cause of Error 167. - Locate the CREATE INDEX Statement: Find the line of code that looks like
CREATE INDEX IX_Name ON @MyTable (ColumnName). This is the line that must be removed. - Modify the Declaration: Go to the
DECLARE @MyTable TABLE (...)section of your script. Instead of creating the index later, add the index definition directly inside the parentheses. - Implement a Primary Key: If the index was intended to be a unique identifier, add
PRIMARY KEYnext to the column definition.
Example:DECLARE @MyTable TABLE (ID Int PRIMARY KEY, Name Varchar(50)) - Implement a Unique Constraint: If the index was meant to ensure uniqueness but not serve as the primary key, use the
UNIQUEkeyword.
Example:DECLARE @MyTable TABLE (ID Int PRIMARY KEY, Email Varchar(100) UNIQUE) - Handle Non-Unique Indexes: If you need a non-unique index on a table variable, you can create a UNIQUE constraint on a combination of the column you want to index and an
IDENTITYcolumn. This effectively creates an index on the target column. - Execute the Script: Run the modified script. The error should now be resolved as the index is created implicitly during the table variable's initialization.
Common Mistakes
- Using CREATE INDEX on @Variables: The most common mistake is treating a table variable like a temporary table. Remember:
CREATE INDEXis for#TempTables; inline constraints are for@TableVariables. - Over-indexing Table Variables: Because table variables are stored in
tempdband have limited statistics, adding too many constraints can sometimes lead to poor execution plans. Only index columns used inJOINorWHEREclauses. - Confusing Table Variables with Temp Tables: Developers often switch between the two. If your logic absolutely requires the ability to add indexes dynamically after data has been inserted, you must use a temporary table (
#TableName) instead of a variable.
Tips
- Choose the Right Tool: Use table variables for very small datasets. For larger datasets where you need the flexibility of
CREATE INDEXor where the query optimizer needs better statistics, use local temporary tables (#). - Check Execution Plans: After moving your index into the
DECLAREstatement, check the execution plan in SSMS to ensure the SQL Server optimizer is actually utilizing the index. - Use Identity Columns: When creating a unique constraint to mimic a non-unique index on a table variable, always use an
INT IDENTITY(1,1)column to ensure the constraint is satisfied without affecting your data logic.
Troubleshooting
If you have moved the index into the DECLARE statement and the query is still slow or behaving unexpectedly:
- Switch to a Temporary Table: If the table variable is large (typically over a few thousand rows), the optimizer may ignore your inline index because table variables do not have distribution statistics. Change
DECLARE @MyTable TABLEtoCREATE TABLE #MyTable. - Verify Column Types: Ensure the data types in your index match the data types in your
JOINconditions. Type mismatches can cause "Implicit Conversion," which prevents the index from being used. - Check for Blocking: If you switched to a temporary table and are now seeing timeouts, ensure you are dropping the table at the end of your session using
DROP TABLE #MyTableto keeptempdbclean.
Frequently Asked Questions
Can I use CREATE INDEX on a #TempTable?
Yes. Local and global temporary tables (starting with # or ##) fully support the CREATE INDEX statement after the table has been created.
Why doesn't SQL Server allow CREATE INDEX on table variables?
Table variables are designed to be lightweight and have a different scope and lifetime than temporary tables. Their structure must be fixed at the time of declaration.
Does a PRIMARY KEY on a table variable create an index?
Yes, defining a PRIMARY KEY or UNIQUE constraint on a table variable automatically creates a supporting index to enforce that constraint.
What is the performance difference between a table variable and a temp table?
Temporary tables generally perform better for large datasets because they support statistics and allow for the creation of indexes after the data is loaded.
Can I add an index to a table variable after I have inserted data?
No. You cannot alter the structure of a table variable after it has been declared. Any indexing must be defined in the initial DECLARE statement.