Search code examples
sql-servertemp-tables

why does updating a real table from a self-join temp table is not working but when using a real table it works?


Here's the scenario:

Procedure 1 creates temp table #t.

Procedure 1 executes procedure 2.

Procedure 2 populates #t.

In procedure 1, I insert into a real table from #t just so I can view the data. The data is there.

Immediately after viewing this data, I do an update with a self-join. Like so:

  update b
  set b.column1 = a.column3
  from #t a
    inner join #t b on a.id = b.id;

The record that is supposed to be updated IS NOT UPDATING.

However, if I change #t to a real table "dbo.t" and do exactly the same thing, it works.

I'm so confused. Anyone has any idea why this could be? Thanks.


Solution

  • Per the MS SQL Docs:

    A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table.

    https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-2017