SQL SERVER 2005 - Take database Offline and close active connections

Working for a hosting company one of the things I have to do every so often is restore customers database backups.

When there is an existing database alrerady in place and in use, you will not be able to do this while there are still active connections open, and you will therefore need to close those conenctions first.

With SQL 2000 this was easy, from enterprise manager you could choose "detach database", and then clear the open connections, then cancel the detach, then restore your backup.

 

As with many things, this is not so easy with SQL Server 2005 as the "SQL Server management Studio Express" doesn't have this option, so here is how to do this with script.

 

EXEC sp_dboption N'mydb', N'offline', N'true'
or
ALTER DATABASE [mydb] SET OFFLINE WITH ROLLBACK AFTER 30 SECONDS
or
ALTER DATABASE [mydb] SET OFFLINE WITH ROLLBACK IMMEDIATE

Using the alter database statement (SQL Server 2k and beyond) is the preferred method. The rollback after statement will force currently executing statements to rollback after N seconds. The default is to wait for all currently running transactions to complete and for the sessions to be terminated. Use the rollback immediate clause to rollback transactions immediately.
After you restore your database, it will automatically come back online.

 

 

 

SQL Server 2005 security and best practices

Like me I bet a lot of you have started playing with SQL Server 2005 and found it to be a completely different beast than SQL Server 2000, especially if you are also getting to grips with the new management studio instead of Enterprise manager, which so far seems to be lacking a few features as far as I can tell ?Security is always an important factor when deploying databases and even more so in a shared environment, so here are a few useful articles to get you on track.

 

SQL Server 2005 Security Overview for Database Administrators
This paper covers some of the most important new security features in SQL Server 2005. It tells you how, as an administrator, you can install SQL Server securely and keep it that way even as applications and users make use of the data stored within.

 

Security Considerations for SQL Server
SQL Server 2005 includes a variety of highly precise, configurable security features that can empower administrators to implement defense-in-depth that is optimized for the specific security risks of their environment. Access guidance about password policy, surface-area configuration, credentials, authenticators, and more.

 

Security Considerations for Databases and Database Applications
The SQL Server 2005 Database Engine helps you protect data from unauthorized disclosure and tampering. Learn about highly granular authentication, authorization, and validation mechanisms; strong encryption; security context switching and impersonation; and integrated key management.

 

SQL Server 2005 Security Best Practices: Operational and Administrative Tasks
This white paper covers some of the operational and administrative tasks associated with SQL Server 2005 security and lists best practices and operational and administrative tasks that will result in a more secure SQL Server system.

 

Protect Sensitive Data Using Encryption in SQL Server 2005
SQL Server 2005 uses strong encryption to provide the best protection for data, a nearly inviolate barrier to exposure. Explore the encryption features in the core database engine of SQL Server 2005, and learn how they can be used to protect data stored there as well as how to allow user interaction with prtected data. Also discussed are the various keys used to protect both data and other keys within a database, and how to get information about encryption objects.

SQL Server Tips and Tricks

Below is my own collection of useful tips for SQL Server 2000. This covers most of the more "not common knowledge" issues I have to deal with quite regulalrly and which you may find yourself having to deal with at least once. I hope you might find this useful.

 

Restoring databases

When restoring a backup database from another server, you will have an orphan user and you need to link the database user to an SQL server login.

The easiest way is to create the original login name on the SQL server, then restore the database backup.

Now run this command against the database from query analyser.

 sp_change_users_login 'auto_fix', 'Login'

 

This will automatically associate the orphaned user with the specified Login.

If you have multiple users in the database that each have their own login, you will need to associate each one like this.

 

sp_change_users_login 'update_one', ‘user', 'Login'

 

This links the specified user in the current database to login. login must already exist. user and login must be specified.

 

Taking a DB offline

 

When taking a DB offline you may need to kill all open connections first, the below stored procedure will allow you to do this. Execute the stored procedure with: 

Exec kill_all "database name"

 


 

------------- copy below this line --------------

CREATE procedure Kill_All  

      @dbname varchar(50) 

as 

Begin 

 -- Declare all the relevant variables

 declare @counter int, 

 @spid int 

 

 -- Temp table to store all the connections

 Create table #StoreConnections 

 ( 

 id int identity(1,1), 

 spid int, 

 kpid int, 

 dbid int 

 ) 

  

 -- Insert all the connection SPIDs ...

 Insert into #StoreConnections 

 Select spid,kpid,dbid from master..sysprocesses where kpid = 0 and dbid = db_id(@dbname) and spid > 40 

 

 Set @counter = 1 

 Set @spid = (Select spid from #StoreConnections where id = @counter) 

 

 -- Start killing all the SPIDs ...    

 While @spid <> ''  

 Begin 

  Select @spid 

  Exec ('Kill ' + @spid) 

  Set @counter = @counter + 1 

  Set @spid = (Select spid from #StoreConnections where id = @counter) 

 End 

 

 -- Cleanup activity. 

 Drop table #StoreConnections 

  

End

--------------- copy above this line ------------

 

Changing Object Ownership

 

When restoring a database backup for a client, often their tables may be owned by the DBO and not their database user.

The script below will change the owner of all tables to the specified 'NewUserName'

 

DECLARE @currentObject nvarchar(517)

DECLARE @qualifiedObject nvarchar(517)

DECLARE @currentOwner varchar(50)

DECLARE @newOwner varchar(50)

 

SET @currentOwner = 'dbo'

SET @newOwner = 'NewUserName'

 

DECLARE alterOwnerCursor CURSOR FOR

SELECT [name] FROM dbo.sysobjects

WHERE xtype = 'U' or xtype = 'P'

AND LEFT([name], 2) <> 'dt'

OPEN alterOwnerCursor

FETCH NEXT FROM alterOwnerCursor INTO @currentObject

WHILE @@FETCH_STATUS = 0

BEGIN

   SET @qualifiedObject = CAST(@currentOwner as varchar) + '.' + CAST(@currentObject as varchar)

   EXEC sp_changeobjectowner @qualifiedObject, @newOwner

   FETCH NEXT FROM alterOwnerCursor INTO @currentObject

END

CLOSE alterOwnerCursor

DEALLOCATE alterOwnerCursor

 

Useful SQL Server Related links


http://www.support.microsoft.com/?id=314546
Moving DB's between Servers

http://www.support.microsoft.com/?id=224071
Moving SQL Server Databases to a New Location with Detach/Attach

http://support.microsoft.com/?id=221465
Using WITH MOVE in a Restore

http://www.support.microsoft.com/?id=246133
How To Transfer Logins and Passwords Between SQL Servers

http://www.support.microsoft.com/?id=298897
Mapping Logins & SIDs after a Restore

http://www.dbmaint.com/SyncSqlLogins.asp
Utility to map logins to users

http://www.support.microsoft.com/?id=168001
User Logon and/or Permission Errors After Restoring Dump

http://www.support.microsoft.com/?id=240872
How to Resolve Permission Issues When a Database Is Moved Between SQL Servers

http://www.sqlservercentral.com/scripts/scriptdetails.asp?scriptid=599
Restoring a .mdf

http://www.support.microsoft.com/?id=307775
Disaster Recovery Articles for SQL Server

http://www.dbmaint.com/SyncSqlLogins.asp

Sync SQL logins

Restrict database view in Enterprise Manager

PROBLEM

When many databases exist in a default instance or in a named instance of Microsoft SQL Server, you may experience a slow response from SQL Server Enterprise Manager, specifically when you drill into the Databases folder. If the Databases folder contains more than a thousand databases, you could experience delays that are more than five minutes.

The other problem is the very fact that on a shared server any user can see all the other databases on the server via Enterprise manager, even if they cannot access them.
The reason this can be an issue is from a security perspective. A lot of clients will have their database username/password hard coded into their DSN, and their DSN will usually have the same name as the database, which means that anyone else hosted on the same ColdFusion server can access that database if they know the DSN, and any les sthan honest person may just try that after seeing the list of databases.
So you may want to restrict this so that a user can only see their own databases.

Here is a link to a Microsoft KB article on how to resolve this issue.