Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. declare @dbName varchar(100)
  2. set @dbName ='MyDatabase'
  3.  
  4. IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = @dbName)
  5. BEGIN
  6.  
  7.  
  8.  
  9. declare @liveConnections as Table(Id int identity(1,1), name varchar(max), spid int )
  10.  
  11.  
  12. insert into @liveConnections (Name,Spid)
  13. select d.name , convert (smallint, req_spid) As spid
  14. from master.dbo.syslockinfo l, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u, master.dbo.sysdatabases d
  15. where l.rsc_type = v.number and v.type = 'LR' and l.req_status = x.number and x.type = 'LS' and l.req_mode + 1 = u.number
  16. and u.type = 'L' and l.rsc_dbid = d.dbid
  17. and rsc_dbid = (select top 1 dbid from master..sysdatabases where name = @dbName)
  18.  
  19.  
  20. if(exists(select 1 from @liveConnections))
  21. BEGIN
  22. declare @counter int=1
  23.  
  24. while(exists(select 1 from @liveConnections where Id=@counter))
  25. BEGIN
  26.  
  27. declare @kill_process nvarchar(max)
  28. declare @spid varchar(100)
  29.  
  30.  
  31. select @kill_process=Name, @spid=cast(spid as varchar(100)) from @liveConnections where id=@counter
  32.  
  33. SET @kill_process = 'KILL ' + @spid
  34. EXEC master.dbo.sp_executesql @kill_process
  35. PRINT 'killed spid : '+ @spid
  36.  
  37. set @counter =@counter +1
  38. END
  39. END
  40.  
  41. exec sp_dboption @dbName, 'single user', 'TRUE'
  42.  
  43.  
  44.  
  45. DROP DATABASE [MyDatabase]
  46. END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement