Connecting to newly created database after previous connection error - sql-server

My application is periodically connecting to MyDatabase and performing a query.
I need to handle the case where the MyDatabase database does not already exist and needs to be created. What I am doing currently is each time I first connect to the master database and run something like this:
SELECT * FROM sysdatabases WHERE NAME='MyDatabase'
to determine whether MyDatabase exists. If it doesn't I create it and then proceed with connecting to MyDatabase and performing the query.
Opening a separate connection to the master database and performing a query each time seems unnecessary (even though the connections are pooled). Why can't I just connect to MyDatabase straight away? 99% of the time it will succeed and I can execute the queries. The 1% of times it fails I can detect MyDatabase is missing and create it at that point right?
But when I try this I hit a problem. If I attempt to connect to MyDatabase and it doesn't exist I get a SqlException
Cannot open database MyDatabase requested by the login. The login failed.
Fine. Great. I can catch any SqlException and then go off to the master database to determine MyDatabase does not exist and create it.
But after creating it, when I now try to connect to MyDatabase I immediately get the same error:
Cannot open database MyDatabase requested by the login. The login failed.
It looks like it isn't trying to connect again and instead is returning a cached result. If I wait 10 seconds after creating the database before attempting to connect to it, the connection succeeds.
My question is, is this caching expected (I guess so) and more importantly is there a best practice for dealing with this situation? Is there perhaps a cache clearance or timeout setting in the SqlConnection API I can use? I could implement my own timeout delay I think but I would like to know there isn't a better method I am missing.

I had exactly the same problem.
When I call the static SqlConnection.ClearAllPools() method before I try to open the newly created database, it works fine!

Related

SQL Server: Restoring DB via linked server - Database intermittently stuck in restoring state (even with RECOVERY option)

I am doing restores across servers via dynamic sql and linked servers as follows:
Exec ('USE MASTER; RESTORE DATABASE <dbname> FROM DISK = <path> WITH REPLACE, RECOVERY') AT <target server>
The database is set to single user mode before the above statement runs. However, on intermittent occasions, when trying to get the database back to multi user mode I get the a query timeout from the the target server and error:
ALTER DATABASE is not permitted while a database is in the Restoring state
I have looked around for this error but apparently I'm should not be getting it when using the RECOVERY option.
Any ideas please?
I managed to figure this out today. The culprit behind the issue was the default remote query time out for Sql Server which is 600s (10mins). More on this in the following link https://msdn.microsoft.com/en-us/library/ms189040(v=sql.105).aspx
My restore usually takes around 10mins to complete, sometimes a bit less so it succeeds and sometimes a bit more when it fails. Hence the issue was manifesting itself intermittently.
I increased the remote query time out on the source server to 36000s and it restored successfully. Just to prove the point, I decreased the remote query time out to a small figure like 60s and got the same symptom again.
Michelle - I set the database in single user to kill any running queries before the restore and to make sure there are no conflicts whilst the database is restored. This would eliminate the Exclusive Access could not be obtained because the database is in use error. Alternatively the database can be put to offline before the restore is initiated and back to online afterwards.

SQL Server tells me database is in use but it isn't

SQL Server keeps telling me a database is in use when I try to drop it or restore it, but when I run this metadata query:
select * from sys.sysprocesses
where dbid
in (select database_id from sys.databases where name = 'NameOfDb')
It returns nothing.
Sometimes it will return 1 process which is a CHECKPOINT_QUEUE waittype. If I try to kill that process, it won't let me (cannot kill a non-user process).
Anyone have any idea what's wrong?
i like this script. Do not struggle with killing..
use master
alter database xyz set single_user with rollback immediate
restore database xyz ...
alter database xyz set multi_user
I was having the same issue when trying to restore a database from a backup. The solution for me was to ensure that I checked "Overrite the existing database(WITH REPLACE)" and "Close existing connections to destination database" in the Options page BEFORE doing the restore. Here is a screenshot below.
There could be lots of things blocking your database. For example, if you have a query window opened on that database, it would be locked by you. Not counting external accesses, like a web application on IIS.
If you really wanna force the drop on it, check the close existing connections option or try to manually stop SQL Server's service.

Drop all active database connections failed for Server when executing KillAllProcesses

I need to perform a database restore from my application. Before doing this, I want to kill all processes as follows:
private void KillAllProcessesOnSMARTDatabases(Server targetServer)
{
targetServer.KillAllProcesses(SMART_DB);
targetServer.KillAllProcesses(SMART_HISTORY_DB);
targetServer.KillAllProcesses(SMART_METADATA_DB);
SqlConnection.ClearAllPools();
}
However, when the first KillAllProcesses is run, I get the following exception:
Microsoft.SqlServer.Management.Smo.FailedOperationException: Drop all active database connections failed for Server 'MYServer'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. ---> System.Data.SqlClient.SqlException: Only user processes can be killed.
The connection string used to create the server has sa credentials, however, the processes that need to be terminated are started under a different user. I tested the similar scenario and the test succeeded.
This started happening only recently. To me it appears there are some processes running that are not started by the user?
It would appear that your code is attempting to terminate all SQL Server Processes, which is not a good idea.
If you want to perform a database restore, you should set the database in question into either single_user mode or RESTRICTED_USER mode, the later being the most suitable.
Take a look at the following example of switching a database to RESTRICTED_USER mode and how to close any open user connections in the process.
How to: Set a Database to Single-User mode
You can use SMO to "kill" a particular database.
This will force a drop of all client connections to that database only and then drop the database itself.
Microsoft.SqlServer.Management.Smo.Server oServer = this.GetSmoServer();
oServer.KillDatabase(this.DatabaseName);

Extreme wait-time when taking a SQL Server database offline

I'm trying to perform some offline maintenance (dev database restore from live backup) on my dev database, but the 'Take Offline' command via SQL Server Management Studio is performing extremely slowly - on the order of 30 minutes plus now. I am just about at my wits end and I can't seem to find any references online as to what might be causing the speed problem, or how to fix it.
Some sites have suggested that open connections to the database cause this slowdown, but the only application that uses this database is my dev machine's IIS instance, and the service is stopped - there are no more open connections.
What could be causing this slowdown, and what can I do to speed it up?
After some additional searching (new search terms inspired by gbn's answer and u07ch's comment on KMike's answer) I found this, which completed successfully in 2 seconds:
ALTER DATABASE <dbname> SET OFFLINE WITH ROLLBACK IMMEDIATE
(Update)
When this still fails with the following error, you can fix it as inspired by this blog post:
ALTER DATABASE failed because a lock could not be placed on database 'dbname' Try again later.
you can run the following command to find out who is keeping a lock on your database:
EXEC sp_who2
And use whatever SPID you find in the following command:
KILL <SPID>
Then run the ALTER DATABASE command again. It should now work.
There is most likely a connection to the DB from somewhere (a rare example: asynchronous statistic update)
To find connections, use sys.sysprocesses
USE master
SELECT * FROM sys.sysprocesses WHERE dbid = DB_ID('MyDB')
To force disconnections, use ROLLBACK IMMEDIATE
USE master
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Do you have any open SQL Server Management Studio windows that are connected to this DB?
Put it in single user mode, and then try again.
In my case, after waiting so much for it to finish I had no patience and simply closed management studio. Before exiting, it showed the success message, db is offline. The files were available to rename.
execute the stored procedure
sp_who2
This will allow you to see if there is any blocking locks.. kill their should fix it.
In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.
In my case I had looked at some tables in the DB prior to executing this action. My user account was holding an active connection to this DB in SSMS. Once I disconnected from the server in SSMS (leaving the 'Take database offline' dialog box open) the operation succeeded.
anytime you run into this type of thing you should always think of your transaction log. The alter db statment with rollback immediate indicates this to be the case. Check this out: http://msdn.microsoft.com/en-us/library/ms189085.aspx
Bone up on checkpoints, etc. You need to decide if the transactions in your log are worth saving or not and then pick the mode to run your db in accordingly. There's really no reason for you to have to wait but also no reason for you to lose data either - you can have both.
Closing the instance of SSMS (SQL Service Manager) from which the request was made solved the problem for me.....
To get around this I stopped the website that was connected to the db in IIS and immediately the 'frozen' 'take db offline' panel became unfrozen.
Also, close any query windows you may have open that are connected to the database in question ;)
I tried all the suggestions below and nothing worked.
EXEC sp_who
Kill < SPID >
ALTER DATABASE SET SINGLE_USER WITH Rollback Immediate
ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE
Result: Both the above commands were also stuck.
4 . Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Result: The window was stuck on executing.
As a last resort, I restarted the SQL server service from configuration manager and then ran ALTER DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE. It worked like a charm
In SSMS, set the database to read-only then back. The connections will be closed, which frees up the locks.
In my case there was a website that had open connections to the database. This method was easy enough:
Right-click the database -> Properties -> Options
Set Database Read-Only to True
Click 'Yes' at the dialog warning SQL Server will close all connections to the database.
Re-open Options and turn read-only back off
Now try renaming the database or taking it offline.
For me, I just had to go into the Job Activity Monitor and stop two things that were processing. Then it went offline immediately. In my case though I knew what those 2 processes were and that it was ok to stop them.
In my case, the database was related to an old Sharepoint install. Stopping and disabling related services in the server manager "unhung" the take offline action, which had been running for 40 minutes, and it completed immediately.
You may wish to check if any services are currently utilizing the database.
Next time, from the Take Offline dialog, remember to check the 'Drop All Active Connections' checkbox. I was also on SQL_EXPRESS on local machine with no connections, but this slowdown happened for me unless I checked that checkbox.
SSMS, especially if running it from your own desktop remotely and not directly within the database server, can be a reason for the long delays in detaching a database. For some reason SSMS may not be able to disconnect any existing "connections" to the database.
We found the process was almost instant when we did it directly from the database server itself. And in fact it killed the attempt from my own desktop SSMS session, and it "took over" and detached the database.
Nothing else suggested here worked.
Thanks
In my case i stopped Tomcat server . then immediately the DB went offline .

Drop a database being accessed by another users?

I'm trying to drop a database from PgAdmin 3 and I get this error message:
ERROR: can't delete current database
SQL state: 55006
how can I force the delete/fix this error, of this database?
Quick fix in PgAdmin: just create another empty database. Select it. Delete the first one. Voila.
You can also connect to the command line without selecting a specific database, and drop your database.
The problem here is not that other users are connected to the database, but that you are.
This post by Leeladharan Achar was helpful for me in working with this error.
It essentially boils down to:
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'target_db'
AND pid <> pg_backend_pid();
DROP DATABASE 'target_db';
Simplest fix for this is restart the postgresql. After that You can get rid of database!
If you want to use the pgAdmin4 interface, you have to first delete/drop the db, then, before waiting for the error, you have to immediatelly disconnect from the same database, then it gets deleted without problem.
Instead of creating new database he can simply connect to postgres database, which is created by default in all new PostgreSQL installations. And even if it is not there - template1 should be always there.
The best method to drop user is below mentioned
Like i have a user name is "X" and it have access permission to database name : "Test" .
And now we are created connection with "Test" database
If we try: drop user "X" this will be definality show below mentioned error:
ERROR: user "X" cannot be dropped because the user has a privilege on some object SQL State=55006
First of all connection should not be created with "Test" db.because it currently use so we are not able to delete the user.
create connection with any of database except eg "Test"
Now again try
drop user test
It should be worked fine on my side,let me know if you are facing issue on your side
The easiest and perhaps the neatest fix is to go to services and stop the PostgreSQL server and then start it, and then run the drop database yourdbname; command again. That should disconnect any sessions and allow you to drop the current database.

Resources