Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 517 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I specify "close existing connections" in sql script

#1
I'm doing active development on my schema in SQL Server 2008 and frequently want to rerun my drop/create database script. When I run

USE [master]
GO

IF EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDatabase')
DROP DATABASE [MyDatabase]
GO

I often get this error

Msg 3702, Level 16, State 4, Line 3
Cannot drop database "MyDatabase" because it is currently in use.

If you right click on the database in the object explorer pane and select the Delete task from the context menu, there is a checkbox which to "close existing connections"

Is there a way to specify this option in my script?
Reply

#2
You can disconnect everyone and roll back their transactions with:

alter database [MyDatbase] set single_user with rollback immediate

After that, you can safely drop the database :)
Reply

#3
Go to management studio and do everything you describe, only instead of clicking OK, click on Script. It will show the code it will run which you can then incorporate in your scripts.

In this case, you want:

ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
Reply

#4
According to the [ALTER DATABASE SET][1] documentation, there is still a possibility that after setting a database to SINGLE_USER mode you won't be able to access that database:

> Before you set the database to SINGLE_USER, verify the AUTO_UPDATE_STATISTICS_ASYNC option is set to OFF. When set to ON, the background thread used to update statistics takes a connection against the database, and you will be unable to access the database in single-user mode.

So, a complete script to drop the database with existing connections may look like this:

DECLARE @dbId int
DECLARE @isStatAsyncOn bit
DECLARE @jobId int
DECLARE @sqlString nvarchar(500)

SELECT @dbId = database_id,
@isStatAsyncOn = is_auto_update_stats_async_on
FROM sys.databases
WHERE name = 'db_name'

IF @isStatAsyncOn = 1
BEGIN
ALTER DATABASE [db_name] SET AUTO_UPDATE_STATISTICS_ASYNC OFF

-- kill running jobs
DECLARE jobsCursor CURSOR FOR
SELECT job_id
FROM sys.dm_exec_background_job_queue
WHERE database_id = @dbId

OPEN jobsCursor

FETCH NEXT FROM jobsCursor INTO @jobId
WHILE @@FETCH_STATUS = 0
BEGIN
set @sqlString = 'KILL STATS JOB ' + STR(@jobId)
EXECUTE sp_executesql @sqlString
FETCH NEXT FROM jobsCursor INTO @jobId
END

CLOSE jobsCursor
DEALLOCATE jobsCursor
END

ALTER DATABASE [db_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [db_name]

[1]:

[To see links please register here]

Reply

#5
I tryed what hgmnz saids on SQL Server 2012.

Management created to me:

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'MyDataBase'
GO
USE [master]
GO
/****** Object: Database [MyDataBase] Script Date: 09/09/2014 15:58:46 ******/
DROP DATABASE [MyDataBase]
GO
Reply

#6
I know it's too late but may be its helps some one. on using this take your database offline

ALTER DATABASE dbname SET OFFLINE


Reply

#7
try this C# code to drop your database

public static void DropDatabases(string dataBase)
{

string sql = "ALTER DATABASE " + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;

using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
{
connection.Open();
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
sql = "DROP DATABASE " + dataBase;
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
}
}
Reply

#8
if you are trying to drop it from you application, your connection string's initial catalog must be "master"
Reply

#9
See below. Do not click OK, but Ctrl + Shift + N, and a new window with the script will be ready for you.

[![Drop Database Dialog for script generation][1]][1]


[1]:
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through