Drop a database being accessed by another users? - database

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.

Related

Azure SQL Database - change user permissions on a read-only database for cross-database queries

We use Azure SQL Database, and therefore had to jump through some hoops to get cross-database queries set up. We achieved this following this great article: https://techcommunity.microsoft.com/t5/azure-database-support-blog/cross-database-query-in-azure-sql-database/ba-p/369126 Things are working great for most of our databases.
The problem comes in for one of our databases which is read-only. The reason it's read-only is b/c it is being synced from another Azure SQL Server to derive its content. This is being achieved via the Geo-Replication function in Azure SQL Database. When attempting to run the query GRANT SELECT ON [RemoteTable] TO RemoteLogger as seen in the linked article, I of course get the error "Failed to update because the database is read-only."
I have been trying to come up with a workaround for this. It appears user permissions are one of the things that do NOT sync as part of the geo-replication, as I've created this user and granted the SELECT permission on the origin database, but it doesn't carry over.
Has anyone run into this or something similar and found a workaround/solution? Is it safe/feasible to temporarily set the database to read/write, update the permission, then put it back to read-only? I don't know if this is even possible - I was told by one colleague that they think it will throw an error along the lines of "this database can't be set to read/write b/c it's syncing from another database..."
I figured out a work-around: Create a remote connection to the database on the ORIGIN server. So simple, yet it escaped me until now. Everything working great now.

creating view in sqlserver

I trying to create view linking 2 tables admins and news
create view v_news as
SELECT [n_id]
,[n_title]
,[n_detail]
,[n_date]
,[n_sdate]
,[n_edate]
,[n_admin]
,[a_name]
,[a_email]
,[a_role]
,[a_status]
FROM hed2.dbo.hed_news,hed2.dbo.hed_admins
where hed_admins.a_id=hed_news.n_admin
This message is displayed:
Command(s) completed successfully.
but there is no view in VIEWS folder.
When I try to run the same query again then it says:
There is already an object named 'v_news' in the database.
I am connected with windows authentication
I tried reconnect and restart sql server but ....
Your view is using ANSI 92 syntax. While this will work for older database versions, it will not work in SQL Server 2012. See Mike Walsh's blog on this topic.
1 - When using SSMS views do not show up right away. Right click and hit refresh.
2 - It is very important to make sure you are in the correct database. I am sure many people, including me, have create an object or two in master. This is the default for a new login.
This can be changed by changing the default database for your login.
3 - Execute the USE command to change the database context (default).
The snippet below is a SQL Server 2012 compliant version.
USE [hed2]
GO
create view v_news as
SELECT [n_id]
,[n_title]
,[n_detail]
,[n_date]
,[n_sdate]
,[n_edate]
,[n_admin]
,[a_name]
,[a_email]
,[a_role]
,[a_status]
FROM dbo.hed_news JOIN dbo.hed_admins ON hed_news.n_admin = hed_admins.a_id
GO
Three things:
You must use JOINS and the way your query is written is bad. Just an observation. Nothing to do with your question.
Did you try running SELECT * FROM v_news? That would return results.
Right click and views in SSMS and select refresh. It will show up in the list
Raj

Connecting to newly created database after previous connection error

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!

MSSQL mirroring error 1499

I`ve got a problem with my mirroring. I have already uses this feature to make 2 db work.
But it was on test bases.
Now when I use my scripts on work DB it throws an error:
Msg 1499, Level 16, State 1, Line 1
Database mirroring error: status 1488, severity 16, state 1, string db_name.
Any suggestions?
you database may be in single user mode
right click the database -> options and select MULTI USER under restrict access
try to check the principal and mirror server names, dtabase name etc. It is possible that there is misprints.
This happened to us recently. We found that SQL set the restored database to single user mode during the restore process.
After some research, we simply restarted SQL server services on the mirror. When SQL started back up, the restored database was in multi-user mode and we were able to initialize mirroring without any issues.
There are other sites out there with answers as well, but they involve taking down the principle database. That was not really an option for us at the time. Here is one example in case restarting the mirror does not help the next person who runs into this.
http://blog.armgasys.com/?p=259
I had some what similar issue this is how I solved it. When I ran wizard for mirroring it created endpoints(first part) successfully but when i tried to turn on mirroring it gave me error.
So I solved it by running below command on both server
USE [master]
alter database [yourdatabase] set partner off;
go
--Secondary already had partner but primary did not
--- then i ran below commands on each server.
USE [master]
ALTER DATABASE [yourdatabase]
SET PARTNER = 'TCP://OtherMachineSQLname.domain.LOCAL:5022';
GO
-- then mirroring started to work.

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.

Resources