Thursday, 14 May 2026

Can we create trigger in temp table in SQL server

No. SQL Server does not allow triggers on temporary tables (# or ##). Temp tables are recreated internally in TempDB and are session-scoped short-lived objects, while triggers require persistent metadata. To avoid performance overhead and complexity, SQL Server blocks trigger creation on temp tables. SQL Server does not allow DML triggers (AFTER or INSTEAD OF) on:

Ø  Local Temp Tables → #Temp

Ø  Global Temp Tables → ##Temp

Ø  Table Variables → @Table

Triggers are supported only on:

Ø  Permanent tables

Ø  Views

Let’s see the demo

--creating a temp table

CREATE TABLE #Emp

(

   Id INT,

   EmpName VARCHAR(50)

);

 Table created. Now creating a trigger on this table

--now creating trigger on Temp table

CREATE TRIGGER trg_Test

ON #Emp

AFTER INSERT

AS

BEGIN

   PRINT 'Inserted...'

END;

GO

Getting Error.

Cannot create trigger on a temporary object.

Below is the reason why not we can create Trigger on the temp table or variable table.

Ø  Temp tables are short-lived (session scoped / auto dropped)

Ø  They reside in TempDB internal scope, not user database scope

Ø  Trigger metadata persistence doesn’t align with temporary object lifecycle

Ø  High TempDB concurrency — triggers would massively slow TempDB

So, SQL Server intentionally blocks it.

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts