To begin with, in the long run I will follow Gordon's advice, that is, I will take the necessary steps to enter a regular table in the database to store information about client applications, which should be available in triggers.
But since this was not possible now due to time limitations (it takes several weeks to get the necessary approvals for the new normal table), I came up with a solution to prevent SQL Server from dropping the global table tempo between check its existence and the MERGE .
There is some information about when SQL Server drops the global temp table; my personal tests showed that SQL Server throws the global temporary table at the moment when the session that created it is closed and any other transactions started in other sessions that changed the data in this table.
My solution was to fake data changes in the global temp table before I even checked its existence. If the table exists at that moment, SQL Server will know that it must support it until the current transaction is complete and cannot be discarded after checking its existence. Now the code looks like this (correctly commented out, since this is a kind of hack):
-- Faking a delete on the table ensures that SQL Server will keep the table until the end of the transaction -- Since
Although I would call it "use it at your own peril and risk," it prevents the global temp table from being used in other sessions in its current use, which bothered me the thread.
Thank you all for your time! (from text editing to answers)
source share