I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.
First, I run across all the connections of said database, and kill them.
DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
Execute ('Kill ' + @spid)
Select @spid = top 1 spid from master.dbo.sysprocesses
where dbid = db_id('dbName')
End
Then, I set the database to a single_user mode
ALTER DATABASE dbName SET SINGLE_USER
Then, I run the restore...
RESTORE DATABASE and whatnot
Kill the connections again
(same query as above)
And set the database back to multi_user.
ALTER DATABASE dbName SET MULTI_USER
This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.