I need to restart a database because some processes are not working. My plan is to take it offline and back online again.
I am trying to do this in Sql Server Management Studio 2008:
use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go
I am getting these errors:
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.
What am I doing wrong?
nalply
26.5k15 gold badges78 silver badges101 bronze badges
asked Jan 12, 2011 at 19:23
4
After you get the error, run
EXEC sp_who2
Look for the database in the list. It’s possible that a connection was not terminated. If you find any connections to the database, run
KILL <SPID>
where <SPID>
is the SPID for the sessions that are connected to the database.
Try your script after all connections to the database are removed.
Unfortunately, I don’t have a reason why you’re seeing the problem, but here is a link that shows that the problem has occurred elsewhere.
http://www.geakeit.co.uk/2010/12/11/sql-take-offline-fails-alter-database-failed-because-a-lock-could-not-error-5061/
answered Jan 12, 2011 at 19:50
bobsbobs
21.8k12 gold badges66 silver badges78 bronze badges
5
I managed to reproduce this error by doing the following.
Connection 1 (leave running for a couple of minutes)
CREATE DATABASE TESTING123
GO
USE TESTING123;
SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6
Connections 2 and 3
set lock_timeout 5;
ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
answered Jan 12, 2011 at 20:11
Martin SmithMartin Smith
436k87 gold badges740 silver badges838 bronze badges
Just to add my two cents. I’ve put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has «only» limited permissions like:
ALTER ANY DATABASE
P.S. I’ve spent hours trying to figure out why the «ALTER DATABASE..» does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here’s my MSDN thread!
answered Jul 20, 2015 at 17:00
I will add this here in case someone will be as lucky as me.
When reviewing the sp_who2 list of processes note the processes that run not only for the effected database but also for master. In my case the issue that was blocking the database was related to a stored procedure that started a xp_cmdshell.
Check if you have any processes in KILL/RollBack state for master database
SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'
If you have the same issue, just the KILL command will probably not help.
You can restarted the SQL server, or better way is to find the cmd.exe under windows processes on SQL server OS and kill it.
answered Jan 8, 2018 at 14:10
AlinaAlina
314 bronze badges
In SQL Management Studio, go to Security -> Logins and double click your Login. Choose Server Roles from the left column, and verify that sysadmin is checked.
In my case, I was logged in on an account without that privilege.
HTH!
answered Dec 28, 2012 at 15:25
MartyMarty
9236 silver badges6 bronze badges
1
Killing the process ID worked nicely for me.
When running «EXEC sp_who2» Command over a new query window… and filter the results for the «busy» database , Killing the processes with «KILL » command managed to do the trick. After that all worked again.
aaaidan
7,0438 gold badges66 silver badges102 bronze badges
answered Jun 27, 2014 at 22:43
0
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn’t able to use any of the alter database commands because an exclusive lock couldn’t be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
answered Feb 9, 2017 at 19:04
Geoff DawdyGeoff Dawdy
8666 gold badges15 silver badges42 bronze badges
In rare cases (e.g., after a heavy transaction is commited) a running CHECKPOINT system process holding a FILE lock on the database file prevents transition to MULTI_USER mode.
answered Aug 14, 2018 at 12:52
mitixmitix
1851 silver badge8 bronze badges
In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to ‘resume data’by right clicking the paused database.
To check if you still have processes running just execute this command:
select percent complete from sys.dm_exec_requests
where percent_complete > 0
answered May 31, 2019 at 14:12
- Remove From My Forums
-
Question
-
Hi!
I’m runing sql script on sql server express 2008 sp2 end i’m getting this error.
«ALter database statement failed line 20, 5069»
in the line 20 i have the «GO» statement
I’ve tried to kill all connections to this database but no result.
plz help me
Answers
-
it works, the problem was the in the authentification mode, when i use SA account it works nicely.
thx
-
Marked as answer by
Nissanna
Wednesday, January 13, 2016 10:28 AM
-
Marked as answer by
All replies
-
Nissanna,
This error occurs because a lock could not be placed in database.
Try to use the statement below to disconnect all users from the database before:
ALTER DATABASE [DBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATTE
Felipe Lauffer MCSA: SQL Server | MCP
-
Can you show us the query ?
What are you trying to do with alter database command ?
From where are you running this command , from SSMS or from something else
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
My Wiki Articles
MVP
-
Nissanna,
This error occurs because a lock could not be placed in database.
Try to use the statement below to disconnect all users from the database before:
ALTER DATABASE [DBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATTE
What are you suggesting would you do the same on your production database which is running . Let us first see what OP’s problem is Alter database can be used to do lot of things .
The above command could be very dangerous if applied out of context
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
My Wiki Articles
MVP
-
Same problem, i get the same error in this statement
-
I’m running this script:
USE [master]
GO
declare @Path nvarchar(512)
SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N’master.mdf’, LOWER(physical_name)) — 1)
FROM master.sys.master_files
WHERE database_id = 1 AND file_id = 1
declare @dbname varchar(100)
set @dbname = ‘dbname’DECLARE @Query VARCHAR(MAX)=»
SET @Query = @Query + ‘CREATE DATABASE ‘+@dbName +’ ON PRIMARY ‘
SET @Query = @Query + ‘( NAME = »’+@dbName +»’, FILENAME = N»’+@path+@dbName +’.mdf» , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) ‘
SET @Query = @Query + ‘ LOG ON ‘
SET @Query = @Query + ‘( NAME = »’+@dbName +’_log», FILENAME = N»’+@path+@dbName +’_log.ldf» , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)’
exec (@Query)ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
GO —>here the pb appears
IF (1 = FULLTEXTSERVICEPROPERTY(‘IsFullTextInstalled’))
begin
EXEC [dbname].[dbo].[sp_fulltext_database] @action = ‘enable’
end
GO
ALTER DATABASE [dbname] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [dbname] SET ANSI_NULLS OFF
GO
ALTER DATABASE [dbname] SET ANSI_PADDING OFF
GO
ALTER DATABASE [dbname] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [dbname] SET ARITHABORT OFF
GO
ALTER DATABASE [dbname] SET AUTO_CLOSE OFF
GO
ALTER DATABASE [dbname] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [dbname] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [dbname] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [dbname] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [dbname] SET CURSOR_DEFAULT GLOBAL
GO
ALTER DATABASE [dbname] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [dbname] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [dbname] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [dbname] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [dbname] SET DISABLE_BROKER
GO
ALTER DATABASE [dbname] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [dbname] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [dbname] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [dbname] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [dbname] SET PARAMETERIZATION SIMPLE
GO -
The script doesn’t contain errors.
Are you sure you have SqlServer 2008 or higher?
Maybe you’re running your script on SqlServer 2005.
Hope this help
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
-
now i’m using sql server express 2008 sp1, i think it’s a problem of user permission
-
Of course requires ALTER permission on the database.
Do you have it?
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
-
i know, of course, but i’m still getting the pb
-
i know, of course, but i’m still getting the pb
Can you just run below part of query and see if database is created
USE [master] GO declare @Path nvarchar(512) SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) FROM master.sys.master_files WHERE database_id = 1 AND file_id = 1 declare @dbname varchar(100) set @dbname = 'dbname' DECLARE @Query VARCHAR(MAX)='' SET @Query = @Query + 'CREATE DATABASE '+@dbName +' ON PRIMARY ' SET @Query = @Query + '( NAME = '''+@dbName +''', FILENAME = N'''+@path+@dbName +'.mdf'' , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) ' SET @Query = @Query + ' LOG ON ' SET @Query = @Query + '( NAME = '''+@dbName +'_log'', FILENAME = N'''+@path+@dbName +'_log.ldf'' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)' exec (@Query)
After this select new query in database and then run rest of the script
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
My Wiki Articles
MVP
-
Proposed as answer by
Ice Fan
Wednesday, January 13, 2016 10:19 AM
-
Proposed as answer by
-
But the database
is successfully created?
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
-
YEs, the database is successfully created with this part
USE [master] GO declare @Path nvarchar(512) SELECT @Path=SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1) FROM master.sys.master_files WHERE database_id = 1 AND file_id = 1 declare @dbname varchar(100) set @dbname = 'dbname' DECLARE @Query VARCHAR(MAX)='' SET @Query = @Query + 'CREATE DATABASE '+@dbName +' ON PRIMARY ' SET @Query = @Query + '( NAME = '''+@dbName +''', FILENAME = N'''+@path+@dbName +'.mdf'' , SIZE = 6144KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) ' SET @Query = @Query + ' LOG ON ' SET @Query = @Query + '( NAME = '''+@dbName +'_log'', FILENAME = N'''+@path+@dbName +'_log.ldf'' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)' exec (@Query)
-
i don’t why, but it works for me with cmd line. i didn’t add any thing.
thx
-
Did you tried my approach and did it worked ?
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
My Wiki Articles
MVP
-
in fact, i’m using this script in installshield 2010, it doesn’t create the database, thought when i run just the script on the cmd line or in SSMS it works nicely, i think that installshield doesn’t execute the EXEC statement.
-
You can put your code in a file (sqlscript.sql) and after that
Try this with the command prompt (CMD.EXE):
osql.exe /U username /P password /S server /d database /i sqlscript.sql /o sqlscript.output
Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
-
it works, the problem was the in the authentification mode, when i use SA account it works nicely.
thx
-
Marked as answer by
Nissanna
Wednesday, January 13, 2016 10:28 AM
-
Marked as answer by
-
Hi Nissanna,
Glad to hear that the issue is resolved. Thanks for your sharing, other community members could benefit from your solution.
Thanks,
Ice fan
Ice Fan
TechNet Community Support
мне нужно перезапустить базу данных, потому что некоторые процессы не работают. Мой план-отключить его и снова включить.
Я пытаюсь сделать это в SQL Server Management Studio 2008:
use master;
go
alter database qcvalues
set single_user
with rollback immediate;
alter database qcvalues
set multi_user;
go
Я получаю эти ошибки:
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.
Msg 5061, Level 16, State 1, Line 4
ALTER DATABASE failed because a lock could not be placed on database 'qcvalues'. Try again later.
Msg 5069, Level 16, State 1, Line 4
ALTER DATABASE statement failed.
что я делаю не так?
9 ответов
мне удалось воспроизвести эту ошибку, выполнив следующие действия.
подключение 1 (оставьте на пару минут)
CREATE DATABASE TESTING123
GO
USE TESTING123;
SELECT NEWID() AS X INTO FOO
FROM sys.objects s1,sys.objects s2,sys.objects s3,sys.objects s4 ,sys.objects s5 ,sys.objects s6
соединения 2 и 3
set lock_timeout 5;
ALTER DATABASE TESTING123 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
в SQL Management Studio перейдите в Security — > Logins и дважды щелкните свой логин. Выберите роли сервера в левом столбце и убедитесь, что установлен флажок sysadmin.
в моем случае я вошел в учетную запись без этой привилегии.
HTH!
убийство идентификатора процесса отлично сработало для меня.
При запуске команды «EXEC sp_who2″ над новым окном запроса… и отфильтровать результаты для» занятой «базы данных, убив процессы с помощью команды «убить» удалось сделать трюк. После этого все снова заработало.
просто добавить мои два цента. Я поставил себя в ту же ситуацию, при поиске минимальных необходимых привилегий входа в БД для успешного выполнения инструкции:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Кажется, что оператор ALTER завершает успешно, при выполнении с администратор login, но для этого требуется часть очистки соединений, при выполнении под логином, который имеет» только » ограниченные разрешения, такие как:
ALTER ANY DATABASE
P. S. Я потратил часов пытаясь выяснить, почему » ALTER DATABASE..»не работает при выполнении под логином, который имеет роль dbcreator + изменить любую базу данных привилегии. Вот мой поток MSDN!
Я знаю, это старый пост, но недавно я столкнулся с очень похожей проблемой. К сожалению, я не смог использовать ни одну из команд alter database, потому что исключительная блокировка не могла быть размещена. Но мне так и не удалось найти открытое соединение с БД. В конце концов мне пришлось принудительно удалить состояние работоспособности базы данных, чтобы заставить ее восстанавливаться, а не восстанавливаться.
Я добавлю это здесь, если кому-то повезет, как мне.
при рассмотрении sp_who2 список процессов, обратите внимание на процессы, которые выполняются не только для базы данных, но и для мастер. В моем случае проблема, которая блокировала базу данных, была связана с хранимой процедурой, которая запустила xp_cmdshell.
проверьте, есть ли у вас какие-либо процессы в убить/отмотка государство мастер база данных
SELECT *
FROM sys.sysprocesses
WHERE cmd = 'KILLED/ROLLBACK'
Если у вас такая же проблема, просто команда KILL, вероятно, не поможет.
Вы можете перезапустить SQL server или лучше найти cmd.exe под Windows обрабатывает на SQL server OS и убивает его.
в редких случаях (например, после тяжелой транзакции) запущенный системный процесс контрольной точки, удерживающий блокировку файла в файле базы данных, предотвращает переход в многопользовательский режим.
29.06.10 — 10:29
Перевел базу в SINGLE_USER для того чтобы протестировать и восстановить, но система вывалила ошибку что типа база уже открыта.
Теперь база висит в SINGLE_USER и обратно ее перевести не могу, не получается даже свойства посмотреть. Выдает ошибку.
«База данных уже открыта, и одновременно к ней может обращаться только один пользователь»
Что сделать? Как отрубить имеющиеся соединения?
1 — 29.06.10 — 10:30
Перезапустить службу не предлагать?
2 — 29.06.10 — 10:30
(1) Ну да, желательно как-нибудь бэз этого
3 — 29.06.10 — 10:34
закрыть базу тем, кем она открыта
4 — 29.06.10 — 10:38
все конечно уже догадались что речь про ms sql.
НО версии ms sql. из какой программмы Вы преводили — не раскрыта.
5 — 29.06.10 — 10:39
alter database MyBse set MULTI_USER
6 — 29.06.10 — 10:42
(5)
Сообщение 5064, уровень 16, состояние 1, строка 1
В настоящий момент невозможно изменить состояние или параметры базы данных «buh_npm_upp». База данных находится в однопользовательском режиме, и в настоящий момент к ней подключен пользователь.
Сообщение 5069, уровень 16, состояние 1, строка 1
Не удалось выполнить инструкцию ALTER DATABASE.
Висит какое-то соединение, но где его посмотреть в SQL Server 2008?
7 — 29.06.10 — 10:45
alter database MyBse set MULTI_USER WITH ROLLBACK IMMEDIATE
+
sp_who
8 — 29.06.10 — 10:47
(7) А это sp_who куда?
9 — 29.06.10 — 10:48
(8) туда же, рядом.
Оно покажет, who is connected
10 — 29.06.10 — 10:53
(9)
alter database buh_npm_upp set MULTI_USER WITH ROLLBACK IMMEDIATE sp_who
Сообщение 102, уровень 15, состояние 1, строка 1
Неправильный синтаксис около конструкции «sp_who».
11 — 29.06.10 — 11:08
up
12 — 29.06.10 — 11:11
иногда надо sp_who2
13 — 29.06.10 — 11:13
(12) Таже фигня
Неправильный синтаксис около конструкции «sp_who2».
А монитором никак нельзя получить? Что-то похожее было в 2005 но в 2008 немогу ничего найти
Zixxx
14 — 29.06.10 — 11:24
upup
Skip to content
At times, we may need to take a database offline. And there is a chance that we encounter an error message like below.
How do we solve this issue and take the database offline?
Msg 5061, Level 16, State 1, Line 1
ALTER DATABASE failed because a lock could not be placed on database 'DBNAME'. Try again later.
Solution:
If there are any connections open, then there is a lock on the database while getting the database into Single user mode/taking offline.
To resolve the issue, as a first step you need to kill all the sessions on the database followed by the ALTER database statement.
USE master;
DECLARE @killSessions varchar(8000) = '';
SELECT @killSessions = @killSessions + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id('dbname')
EXEC(@killSessions);
ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE dbname SET OFFLINE WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE dbname SET MULTI_USER;