| 
 | 
								
									
										|  |  
										|  |  
										| | Few days ago I came up with one problem. I was tesing a script in query analyzer. This script was using several temp tables so every time I run this script I had to make sure that all temp tables are dropped before I run the script otherwise it will give bunch of errors. So I decided to write a procedure to drop all temp tables created by your current session. 
 you can call the following procedure before running your T-SQL script. If you are running stored procedure then all temp tables are automatically deleted when execution is complete but for batch script temp tables remain in tempdb until you close the connection (i.e. close the Query Analyzer Window).
 | 
 |  Click here to copy the following block |  | ALTER  proc usp_DropAllTemp @DropGlobal bit=0
 AS
 
 DECLARE @DROP_STATEMENT nvarchar(1000)
 DECLARE cursorDEL CURSOR FOR
 SELECT 'DROP TABLE '
 + case
 when name like '##%' then name
 when name like '#%' then SUBSTRING(name, 1, CHARINDEX( '____', name)-1)
 end as DropSQL
 from tempdb..sysobjects
 WHERE name LIKE '#%'
 AND OBJECT_ID('tempdb..' + name) IS NOT NULL
 AND name not like case
 when @DropGlobal=0 then '##%'
 else '#######%'
 
 end
 
 
 
 
 
 OPEN cursorDEL
 FETCH NEXT FROM cursorDEL INTO @DROP_STATEMENT
 WHILE @@FETCH_STATUS = 0
 BEGIN
 EXEC (@DROP_STATEMENT)
 print @DROP_STATEMENT
 FETCH NEXT FROM cursorDEL INTO @DROP_STATEMENT
 END
 CLOSE cursorDEL
 DEALLOCATE cursorDEL
 
 GO
 | 
 |  
										|  |  
										|  |  
 
	
		| Submitted By :
					Nayan Patel 
					 (Member Since : 5/26/2004 12:23:06 PM) |  
		|  |  
		| 
				 | Job Description :   
			He is the moderator of this site and  currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |  
		| View all (893) submissions by this author 
			(Birth Date : 7/14/1981 ) |  |  |