SQL Server Error 1766: Foreign Keys on Temp Tables
In this article
SQL Server error 1766 — "Foreign key references to temporary tables are not allowed" — appears when you try to create a foreign key that points to a temporary table (a table whose name starts with a single # or a double ##). SQL Server does not support foreign key constraints on temporary tables at all: you cannot reference a temp table from a permanent table, and you cannot create a foreign key inside a temp table that points to another temp table either. The fix is to remove the foreign key from the temp table definition and enforce the relationship in your code instead — with joins, existence checks, or a trigger on the permanent table. This guide walks through the cause, the safe rewrite, and the alternatives that actually work.
What You'll Need
- Access to the database where the error occurs (SSMS, Azure Data Studio, or sqlcmd).
- The script or stored procedure that creates the temp table, so you can edit the constraint out.
- Permission to create and alter tables in the target database, or a DBA who can apply the change.
- A way to test in a non-production copy if the script is part of a live job.
Step-by-Step
- Confirm the error is 1766. Run the failing statement in SQL Server Management Studio (SSMS) or Azure Data Studio and read the message. Error 1766 reads: "Foreign key references to temporary tables are not allowed. Foreign key '%.*ls'." The constraint name in the message tells you which foreign key to remove. Menu labels in SSMS can differ slightly by version, but the query window and error output are the same across versions.
- Find the offending constraint. Search your script for
FOREIGN KEY,REFERENCES, and the constraint name from the error. Typical culprits are aCREATE TABLE #Orders (... CONSTRAINT FK_Orders_Customer FOREIGN KEY (CustomerID) REFERENCES #Customer(CustomerID))block, or anALTER TABLEthat adds a foreign key to a temp table after creation. Also check for a permanent table that references a##globaltemp table — that is also blocked. - Remove the foreign key from the temp table definition. Delete the
CONSTRAINT ... FOREIGN KEY ... REFERENCES ...clause from theCREATE TABLE #...statement, or drop theALTER TABLE ... ADD CONSTRAINTline. Keep the column and its data type; only the constraint goes. If the constraint was created by a tool or ORM, regenerate the script without foreign keys for temp tables. - Enforce the relationship in code instead. For a parent-child link between two temp tables, join them when you read or write data and filter with
EXISTSor an inner join. For example, before inserting into#Orders, runIF NOT EXISTS (SELECT 1 FROM #Customer WHERE CustomerID = @CustomerID) ...and skip or raise an error for orphan rows. This gives you the same referential check at the point where it matters. - If the relationship must survive across sessions, use a permanent table. Create a real staging table in a schema (for example
dbo.StagingOrders) with a normal foreign key to the permanent parent table, load into it, then merge into the final table. Permanent tables support foreign keys; temp tables do not. Clean up the staging rows after the load, and remember that permanent tables are visible to other sessions, so use a session or batch identifier column to keep concurrent loads apart. - If you need a constraint on a permanent table that references temp data, reverse the direction. You cannot make a permanent table point at a temp table. Instead, load the temp data into a permanent table first, then add the foreign key on the permanent table. Run the
ALTER TABLE ... WITH CHECK ADD CONSTRAINT ... FOREIGN KEY ... REFERENCES ...after the load, and validate withDBCC CHECKCONSTRAINTSif the data came from an untrusted source. - Re-run the script and verify. Execute the corrected batch in a test database. Check that no error 1766 appears, that row counts match expectations, and that orphan rows are rejected by your
EXISTSchecks. If the script is in a stored procedure or SQL Agent job, deploy the change and run the job once manually to confirm.
Common Mistakes
- Trying to disable the constraint instead of removing it.
NOCHECKandWITH NOCHECKdo not help: the constraint cannot be created on a temp table in the first place, so there is nothing to disable. - Assuming a global temp table (
##) behaves like a permanent table. Global temp tables are still temporary tables for this rule; foreign keys are not allowed on them or to them. - Leaving the constraint in a generated script. ORMs and schema comparison tools often regenerate the foreign key. Add the temp-table exclusion to your script generator or post-process the output.
- Replacing the foreign key with a trigger on a temp table and expecting it to fire reliably. Triggers on temp tables exist but are scoped to the session and are easy to miss; explicit
EXISTSchecks are simpler and more predictable. - Forgetting to clean up permanent staging tables. If you switch to a permanent staging table, rows left behind can collide with the next run or leak data between users. Delete by batch or session ID at the end of the job.
Tips
- Keep referential checks close to the insert: a single
IF NOT EXISTSbefore the insert is cheaper to debug than a constraint that fails halfway through a batch. - Use
MERGEorINSERT ... SELECT ... WHERE EXISTSto load only rows that have a matching parent, which prevents orphan rows without a foreign key. - If the logic is complex, put the validation in a stored procedure and return a clear error message listing the orphan keys, so the caller knows what to fix.
- For ETL-style loads, a permanent staging table with a real foreign key is often the cleanest design: it gives you constraint enforcement and survives across steps.
- Document the change in the script comments so the next person does not re-add the foreign key to the temp table.
Troubleshooting
The error persists after removing the constraint from the CREATE TABLE. Search the whole batch for a second REFERENCES clause, including inside dynamic SQL strings and inside ALTER TABLE statements. Error 1766 names the constraint, so match that name exactly.
You need the constraint for data integrity but cannot use a permanent table. Enforce it with a check before insert and a periodic orphan query (SELECT ... FROM #Child c LEFT JOIN #Parent p ON ... WHERE p.Key IS NULL). Run the orphan query after each load step and raise an error if it returns rows.
The script works in one environment but fails in another. Compare the schema: a permanent table in one database may already have a foreign key that references a table name that resolves to a temp table in the other. Check object names and schemas, and confirm both environments run the same script version.
You see a different foreign key error after the fix. Errors such as 547 (constraint conflict) mean the foreign key now exists on a permanent table but the data violates it. Clean the orphan rows first, then re-enable or re-create the constraint with WITH CHECK.
You cannot change the script because it is vendor-supplied. Wrap the load in a staging step: run the vendor script into permanent staging tables, or intercept the temp-table creation with a post-processing step that strips foreign keys. Do not edit vendor code in place without a change record.
Frequently Asked Questions
Can a temp table have a foreign key at all?
No. SQL Server does not allow foreign key constraints on temporary tables, whether the key points to another temp table or to a permanent table. The constraint must be enforced in code or moved to a permanent table.
Does error 1766 apply to table variables?
Table variables (DECLARE @t TABLE ...) also do not support foreign key constraints. The same workaround applies: validate with joins or EXISTS checks.
Can a permanent table reference a global temp table?
No. A foreign key from a permanent table to a ##global temp table is also rejected. Use a permanent staging table instead.
Is there a trace flag or setting that enables foreign keys on temp tables?
No. There is no supported configuration that turns this on. The restriction is part of the product's design, not a setting you can change.
What is the best replacement for a foreign key on a temp table?
An EXISTS check before insert, an inner join when loading, or a permanent staging table with a real foreign key. Choose based on whether the data must persist across sessions.
Will removing the foreign key break my application?
Only if the application relied on the database to reject orphan rows. Add the equivalent check in the load code and test with known orphan data before deploying.