In SQL Server 2008 ,is it possible to disable auto drop of global temp table

╄→гoц情女王★ 提交于 2019-12-08 10:45:32

问题


Question 1: I am using a global temp tables in SQL Server 2008. But once my connection is closed this temp is dropped. Is there any way to disable auto drop

Question 2: If two connections are accessing same global temp table and another connection is trying to delete that global temp table, does SQL Server handles this synchronization properly?


回答1:


You can create your global temp tables in a stored procedure and mark it with the startup option.

SQL Server maintains a reference count greater than zero for all global temporary tables created within startup procedures.

some example code

CREATE PROC dbo.CreateGlobalTempTables
AS
CREATE TABLE ##my_temp_table
(
   fld1 INT NOT NULL PRIMARY KEY,
   fld2 INT NULL
);
GO

EXEC dbo.sp_procoption 'dbo.CreateGlobalTempTables', 'startup', 'true';

The global temporary table will be created automatically at startup and persist until someone explicitly drops it.




回答2:


If you need a table to persist beyond the death of the connection that created it, you should just create a regular table instead of a temporary one. It can still be created in tempdb directly (geting you the benfits of simple logging and auto destruction on server restart) but it's name wouldn't be prefixed by ##.

DROP TABLE is a transactional statement that will block if there are any active connections using that table (with locks).




回答3:


When the connection that created the ##GlobalTempTable ends, the table will be dropped, unless there is a lock against it.

You could run something like this from the other process to keep the table from being dropped:

BEGIN TRANSACTION
    SELECT TOP 1 FROM ##GlobalTempTable WITH (UPDLOCK, HOLDLOCK)


...COMMIT/ROLLBACK

However, when the transaction ends, the table will be dropped. If you can't use a transaction like this, then you should use a permanent table using the Process-Keyed Table method.



来源:https://stackoverflow.com/questions/2826282/in-sql-server-2008-is-it-possible-to-disable-auto-drop-of-global-temp-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!