开发者

How to get the current sproc session ID and drop a temp table existing in that sproc instance?

开发者 https://www.devze.com 2023-04-12 18:00 出处:网络
I\'m using sql2000 and I want to automatically drop a #temp table in a sproc instance or in a query window.This is more for testing purposes than production.Is there a way to get the current session o

I'm using sql2000 and I want to automatically drop a #temp table in a sproc instance or in a query window. This is more for testing purposes than production. Is there a way to get the current session or sproc instance or eve开发者_如何转开发n a query instance, and use that to delete only #temp tables in that instance. I don't want to drop #temp tables in other instances.

I noticed another Stack Overflow question used this code:

declare @sql nvarchar(max) 
select @sql = isnull(@sql+';', '') + 
                                     'drop table ' + quotename(name) from tempdb..sysobjects 
where name like '#%' exec (@sql) 

I just want to detect only #tmp tables in current session or instance. I also will need to do this in sql2008. thx

Thanks.


Your current SPID, again this works on 2005 and up I have not tested it on a 2000 instance

select @@SPID  

shows what you are doing in that spid workins in 2005 and up not sure about the 2000 version

dbcc inputbuffer(54)   

Find spids and kernel threads before execute the test take a screen shot

   select spid, kpid, status, hostname, dbid, cmd
   from master..sysprocesses

Run the SQL again once you start your testing
reference this site http://support.microsoft.com/kb/117559

To drop your temp table if you know the names you can expand on this to get the desired result

IF object_ID('tempdb..#MyTempTable') is not null
begin
    drop table #MyTempTable
end


create table #MyTempTable
(id int);

insert into #MyTempTable (id) values (1);

select * from #MyTempTable

select * from tempdb.sys.tables
where object_id = object_id('tempdb..#MyTempTable')

IF object_ID('tempdb..#MyTempTable') is not null
begin
    drop table #MyTempTable
end


Just KILL the process with the SPID that you are suspecting, and then all temp tables (local and global) will be dropped.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号