473,402 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

T-SQL CLOSE Connection to DB

How do i close a current connection to a database using t-sql?
I fail some time to drop the database getting messages that it's
currently in use.
Using the wizard to delete the database, i could check the option to
close all connections to the db, but how do i do it using t-sql?

best regards

May 28 '06 #1
10 62248
coosa (co*****@gmail.com) writes:
How do i close a current connection to a database using t-sql?


USE <someotherdb>

--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 28 '06 #2
I did actually,

USE [Master];
GO

IF EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDB')
BEGIN
PRINT N'Database [MyDB] already exists';
DROP DATABASE MyDB;
END
GO

May 28 '06 #3
Similary, is there a similar command like 'disconnect' such as in DB2?

May 28 '06 #4
coosa (co*****@gmail.com) writes:
Similary, is there a similar command like 'disconnect' such as in DB2?


I don't know what DISCONNECT in DB2, but the only way to disconnect from
the server with a T-SQL command is SHUTDOWN WITH NOWAIT. Or a RAISERROR
with a severity level >= 20. I would not recommend any of them.

The proper way to disconnect is to do it from the client.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
May 28 '06 #5
On 27 May 2006 19:48:27 -0700, coosa wrote:
How do i close a current connection to a database using t-sql?
I fail some time to drop the database getting messages that it's
currently in use.


Hi coosa,

If you want to disconnect YOUR OWN connection to a database, check out
Erland's reply.

If you need to do maintenance but can't because OTHER people still have
open connections to a database, then you might want to use one of the
following

ALTER DATABASE <dbname> SET SINGLE_USER

or

ALTER DATABASE <dbname> SET SINGLE_USER WITH ROLLBACK_IMMEDIATE

The first version will allow curent connection to finish their business
and commit their work. The latter option immediately disconnects all
open conenctions and rolls back any changes from unfinished
transactions.

--
Hugo Kornelis, SQL Server MVP
May 28 '06 #6
That might be it; some thing remotly is still in use. Then, is there a
way to determine which connections are being used and wait for them but
prevent any new connections?

May 29 '06 #7
On 28 May 2006 18:46:15 -0700, coosa wrote:
That might be it; some thing remotly is still in use. Then, is there a
way to determine which connections are being used
Hi coosa,

EXEC sp_who2;
and wait for them but
prevent any new connections?


ALTER DATABASE <dbname> SET SINGLE_USER;

(By _not_ adding the WITH ROLLBACK_IMMEDIATE option, you tell SQL Server
to disallow new connections but wait until existing connections are
broken before setting the DB to single user)

Note that many front-end programs keep their connection open, mostly
being idle while the person on the screen enters data, answers a phone
call or visits the water cooler. If you waiting for those connections to
close, you won't have your DB in single-user state before the office
closes.

--
Hugo Kornelis, SQL Server MVP
May 29 '06 #8
It's interesting what's happening ...
i run:
USE Master;
GO
EXEC sp_who2;
GO

The 'MyDb' is still under the status RUNNABLE for the command 'SELECT
INTO' under the ProgamName 'Microsoft SQL Server Management Studio -
Query'.
I run the command again after a minute and it disappears.
It seems when i swith the use to a different DB, the change has no
IMMEDIATE effect.
Again, using the "Management Studio", by right clicking the Database
Name and choosing to "Delete", two check boxes can be selected and the
latter is "Close existing Connections" and it never failed to delete.
I have used the suggestion of usning both "ALTER DATABASE <dbname> SET
SINGLE_USER WITH ROLLBACK_IMMEDIATE" and "ALTER DATABASE <dbname> SET
SINGLE_USER" but it's the same. Erland suggestion recommnds stoping the
entire server which i can't afford since there are other databases
running.

May 29 '06 #9
On 29 May 2006 08:22:10 -0700, coosa wrote:
It's interesting what's happening ...
i run:
USE Master;
GO
EXEC sp_who2;
GO

The 'MyDb' is still under the status RUNNABLE for the command 'SELECT
INTO' under the ProgamName 'Microsoft SQL Server Management Studio -
Query'.
I run the command again after a minute and it disappears.
It seems when i swith the use to a different DB, the change has no
IMMEDIATE effect.
Hi coosa,

Very strange. I have never experienced or heard this before. And I was
unable to reproduce - when I ran the code above, sp_who2 reported the
connection to be runnable in the master DB.
Again, using the "Management Studio", by right clicking the Database
Name and choosing to "Delete", two check boxes can be selected and the
latter is "Close existing Connections" and it never failed to delete.
Under the hood, Management Studio uses the ALTER DATABASE command I
suggested, with the ROLLBACK_IMMEDIATE option. This is easy to verify:
make a DB, open some windows in MS to connect to this test DB, then
right-click the DB, click "Delete", check "Close existing connections",
then instead of clicking "OK", click "Script / Script to Clipboard".
Finally, paste the contents of the clipboard in a query window or in a
text file. Here's what was generated on my computer:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'Temp'
GO
USE [master]
GO
ALTER DATABASE [Temp] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
/****** Object: Database [Temp] Script Date: 05/30/2006 00:53:16
******/
DROP DATABASE [Temp]
GO
I have used the suggestion of usning both "ALTER DATABASE <dbname> SET
SINGLE_USER WITH ROLLBACK_IMMEDIATE" and "ALTER DATABASE <dbname> SET
SINGLE_USER" but it's the same.
What does "the same" mean? Do you get any error messages? If so, what
messages?

What happpens if you open a query window in SSMS, then type (or copy)
and execute the query below (replacing MyDB [twice!] with the actual
name of the DB you want to drop). If you get any errors, please copy and
paste the exact messages into a reply to this message (unless you're
running a localized Cyrillic or similar installation - in that case, a
translation is actually preferred <g>)

USE master
go
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK_IMMEDIATE
go
DROP DATABASE MyDB
go

Of course, you should replace MyDB with the real name of your database
(two times!)
Erland suggestion recommnds stoping the
entire server which i can't afford since there are other databases
running.


Erland though you were asking how to force connection to the _SERVER_ to
be broken. For dropping a database, it suffices to break the connection
to the _database_. I know Erland well enough to be 100% sure that he'd
never recommend shutting down a server to drop connections to a DB.

--
Hugo Kornelis, SQL Server MVP
May 29 '06 #10
my appologies then to Erland for this misunderstanding.

May 30 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: dw | last post by:
Which is the most efficient way to hit the database: 1) to open/close the connection for each call to the database on a page (we have Subs that do this); 2) or use the same connection and close it...
4
by: billd | last post by:
I have a function that returns a SqlDataReader created by: result = command.ExecuteReader(CommandBehavior.CloseConnection); I then bind the result to a grid control: myDataGrid.DataSource =...
3
by: Craig | last post by:
I have some methods that open a database connection, get some data and then return a datareader. How do I manage closing the connection to the database then? public OracleDataReader...
4
by: mescano | last post by:
I am currently implementing a singleton pattern for accessing a database. Is it advisable to close the connection to the database at all -- thus leaving it open or should it be closed. If closed,...
5
by: Varangian | last post by:
Hello there people, I'm having some kind of problem. I have a function that returns a datareader. At some point using the application I get an error "Unspecified error" (ssssoooo helpful) :). I...
0
by: bonita | last post by:
In my ASP.NET page, I have 2 checkboxes for users to choose which crystal report they want to display. These two reports use different tables. If report1 has been choosen and displayed in the...
3
by: DavideR | last post by:
I'm working with vs2005 (vb.net) i need to detach a database autoclose property is set to true close cursor on commit is set to true i use the sp_detach with adodb (the program has been converted...
6
by: Jack | last post by:
I have a WebRequest object that I use to log into a site and then post some XML. In doing this I set the KeepAlive = true so that it maintains the connection and does operates undo the initial...
4
by: Max2006 | last post by:
Hi, I saw the Business Logic Layer pattern suggested at the following link and I found that the pattern never closes the connection: ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.