Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

20110221

Disconnecting users from MSSQL database

When trying to restore database from backup often error saying about connected users is displayed.
Script below kills all connections to given database.
Just replace XYZ with required database name.
Remember that all connections will be dropped without notice.

USE master

GO

DECLARE @userId varchar(10) 

DECLARE cur CURSOR READ_ONLY      
FOR 
SELECT request_session_id
FROM master.sys.dm_tran_locks     
WHERE resource_type = 'DATABASE'     
AND resource_database_id = db_id('XYZ')    
GROUP BY request_session_id

OPEN cur     

FETCH NEXT FROM cur INTO @userId      
WHILE (@@fetch_status <> -1)      
BEGIN      
 IF (@@fetch_status <> -2)      
 BEGIN      
  PRINT 'Killing connection ' + @userId      
  EXEC ('KILL ' + @userId)      
 END      
 FETCH NEXT FROM cur INTO @userId      
END      
      
CLOSE cur      
DEALLOCATE cur      

20100315

Shrinking MSSQL log files

Best solution I've found below.
You just have to replace XYZ with database name in few places.
You can also uncomment print to get filename.
Yes, I know it would be useful to have version that iterates through all the databases - I'm just too lazy.

alter database XYZ set recovery simple
GO
alter database XYZ set recovery full
GO
use XYZ
GO
declare @filename sysname
select @filename=Name from sys.database_files where Type=1
--print @filename
DBCC Shrinkfile(@filename,100) 
GO
alter database XYZ set recovery bulk_logged
GO